-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_linked_list_non_recursive.cpp
134 lines (125 loc) · 3.26 KB
/
reverse_linked_list_non_recursive.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
// 什么是链表的翻转:给定链表 head–>4—>3–>2–>1,将其翻转成 head–>1–>2–>3–>4 ,由于翻转链表是如此常见,如此重要
// 所以我们分别详细讲解下如何用递归和非递归这两种方式来解题
// 递归翻转
#include <iostream>
#include <array>
#include <algorithm>
using namespace std;
struct NODE {
int data;// 结点的数组域,值
NODE* next = nullptr;// 节点的引用,指向下一个节点
NODE(int inData)
{
data = inData;
}
};
class LINKED_LIST {
private:
NODE* head;
public:
LINKED_LIST() {
head = new NODE(0);
}
void PrintLink()
{
NODE* tmp = head->next;
while (tmp != nullptr) {
cout << tmp->data << ' ';
tmp = tmp->next;
}
cout << endl;
}
void AddNode(int data)
{
NODE* tmp = head;
while (tmp->next != nullptr) {
tmp = tmp->next;
}
tmp->next = new NODE(data);
}
void HeadInsert(int data)
{
NODE* tmp = new NODE(data);
tmp->next = head->next;
head->next = tmp;
}
NODE* ReturnNode(int pos)
{
int i = 0;
NODE* tmp = head->next;
while (i < pos) {
i++;
tmp = tmp->next;
}
return tmp;
}
void DelNode(NODE* delNode)
{
if (delNode->next == nullptr) {
NODE* beforeDelNode = head;
while (beforeDelNode->next != delNode) {
beforeDelNode = beforeDelNode->next;
}
beforeDelNode->next = nullptr;
// delete delNode;
free(delNode);
} else {
NODE* nextNode = delNode->next;
delNode->data = nextNode->data;
delNode->next = nextNode->next;
// delete nextNode;
free(nextNode);
}
}
void PrintNodePos()
{
NODE* tmp = head->next;
while (tmp != nullptr) {
printf("%d %p\n", tmp->data, tmp);
tmp = tmp->next;
}
printf("FINAL NEXT: %p\n", tmp);
}
NODE* ReverseLinkedListRecur(NODE *node)
{
NODE* tmp = nullptr;
if (node->next != nullptr) {
tmp = ReverseLinkedListRecur(node->next);
node->next->next = node;
node->next = nullptr;
return tmp;
} else {
return node;
}
}
void iterationInvertLinkedList()
{
NODE* pre = head->next;
NODE* cur = pre->next;
pre->next = nullptr;
while (cur->next != nullptr) {
NODE* nextN = cur->next;
cur->next = pre;
pre = cur;
cur = nextN;
}
cur->next = pre;
head->next = cur;
}
};
int main()
{
LINKED_LIST oneLink;
// LINKED_LIST* oneLink1 = new LINKED_LIST();
// printf("the oneLink1 is %p\n", &oneLink1);
oneLink.AddNode(1);
oneLink.AddNode(2);
oneLink.AddNode(3);
oneLink.HeadInsert(0);
oneLink.PrintLink();
oneLink.iterationInvertLinkedList();
// h 0 1 2 3
// h 0 3 2 1
oneLink.PrintLink();
return 0;
}