-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path双向链表.cpp
146 lines (146 loc) · 2.06 KB
/
双向链表.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
struct Node
{
int data;
Node *pre,*next;
}*head,*plast;
void input()
{
Node *pnext;
head=(Node*)malloc(sizeof(Node));
if(head==NULL)
{
cout<<"something wrong!"<<endl;
return ;
}
head->next=NULL;
head->pre=NULL;
cout<<"please input your data (when input -1 it will stop)"<<endl;
plast=head;
while(1)
{
int n;
cin>>n;
if(n==-1)
break;
pnext=(Node*)malloc(sizeof(Node));
pnext->data=n;
plast->next=pnext;
pnext->pre=plast;
plast=pnext;
}
plast->next=NULL;
cout<<"over input! press enter to continue......"<<endl;
getchar();
// system("cls");
}
void output1()
{
Node *temp;
Node *p;
temp=head;
cout<<"positive sequence:"<<endl;
while(temp->next!=NULL)
{
p=temp->next;
cout<<p->data<<endl;
temp=temp->next;
}
}
void output2()
{
Node *temp;
Node *p;
temp=plast;
cout<<"reverse sequence:"<<endl;
while(temp!=head)
{
p=temp;
cout<<p->data<<endl;
temp=temp->pre;
}
}
void insert()
{
int n;
Node *p;
Node *temp;
int i=1;
p=head;
cout<<"please input the number of the one you want to insert in"<<endl;
cin>>n;
while(i<n && p!=NULL)
{
i++;
p=p->next;
}
cout<<"please input your data"<<endl;
int d;
cin>>d;
temp=(Node*)malloc(sizeof(Node));
temp->data=d;
if(p==NULL)
{
cout<<"the data you input will insert in the last"<<endl;
temp->pre=p;
p->next=temp;
temp->next=NULL;
plast=temp;//important
}
else
{
temp->pre=p;
temp->next=p->next;
p->next->pre=temp;
p->next=temp;
}
cout<<"the new result:"<<endl;
output1();
output2();
}
void deleteNode()
{
int n;
int i=1;
Node *p;
Node *d;
p=head;
cout<<"please input the number you what to delete"<<endl;
cin>>n;
while(i<n && p!=NULL)
{
i++;
p=p->next;
}
if(p==NULL)
{
cout<<"error!"<<endl;
return ;
}
d=p->next;
if(d->next!=NULL)
{
p->next=d->next;
d->next->pre=p;
}
else
{
p->next=NULL;
plast=p;//important
}
cout<<"the new result:"<<endl;
output1();
output2();
}
int main()
{
input();
output1();
output2();
insert();
deleteNode();
return 0;
}