文章目录

创建单链表,并逆置(C++实现)

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
#include<iostream>  
using namespace std;

//创建链表节点结构体
struct node
{
int data;
node* next;
};

//创建链表
node *create()
{

node *head;
head = (node *)malloc(sizeof(node)); //为head指针分配空间
head->next=NULL;
head->data =0;
node *p = head; //创建尾指针
cout<<"Please input all the data and end with '-1': "<<endl;
int x;
node *s;

while (cin>>x)
{
if (-1 != x)
{
s = (node *)malloc(sizeof(node)); //分配空间
s->data = x;
p->next =s;
p = s;
head->data++;
}
else
{
break;
}
}
p->next =NULL;
return head;
}

//打印链表
void print(node* head)
{

if(NULL == head || NULL == head->next)
{
cout<<"链表为空"<<endl;
}
node* temp = head->next;
while(temp != NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}

//逆置函数
node *reverse(node *head)
{

node *p1, *p2, *p3;//需要三个辅助节点
if (NULL == head || NULL == head->next)//检查边界情况
{
cout<<"链表为空"<<endl;
return head;
}

p1 = head->next;
p2 = p1->next;
p1->next = NULL;
while (NULL != p2)
{
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
head->next = p1;
return head;
}

int main()
{

node* list = create();
print(list);
reverse(list);
print(list);

system("pause");
return 0;
}
文章目录