-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseSigleLink.cpp
101 lines (85 loc) · 1.6 KB
/
ReverseSigleLink.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
#include<iostream>
#include<stdio.h>
using namespace std;
typedef struct Node List;
struct Node
{
char key;
List * next;
};
List * myhead;
void InserNode(List * node)
{
if(NULL == myhead)
{
myhead = node;
myhead->key = node->key;
}
else
{
node->next = myhead;
myhead = node;
}
}
List *makeNode(char key)
{
List *p = new List;
p->key = key;
p->next = NULL;
return p;
}
List* reverse(List *n)
{
if(!n || !n->next) //判断链表是否为空,为空即退出。
{
return n;
}
List *head= n->next; //保存头结点
List *cur = n; //当前处理结点
List *tmp;
//printf("cur->key = %d\n",cur->key);
cur->next = NULL; //头结点的指针指空,转换后变尾结点
while ( NULL != head->next ) //循环直到 cur.next 为空
{
tmp = head->next;
head->next = cur;
cur = head;
head = tmp;
//printf("cur->key = %d\n",cur->key);
}
head->next = cur;
return myhead = head; //f 返回头指针m
}
void showAll()
{
for(List*p = myhead;p != NULL;p = p->next)
{
printf("p->key = %d\n",p->key);
}
}
List * reverseLink(List *Head)//递归算法实现单链表翻转
{
if(Head->next == NULL)
return Head;
List *rHead = reverseLink(Head->next);
Head->next->next = Head;
Head->next = NULL;
return rHead;
}
int main(int argc, char *argv[])
{
List * p;
for(int i = 1; i<= 10; i++)
{
p = makeNode(i);
if(!p)
cout << p->key << endl;
InserNode(p);
}
showAll();
cout << endl;
//reverse(myhead);
reverseLink(myhead);
showAll();
return 0;
}