-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist.cpp
executable file
·125 lines (86 loc) · 1.85 KB
/
linkedlist.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
#include <iostream>
class Node {
public:
int data;
Node * next;
Node(int val, Node * nextNode): data(val), next(nextNode)
{
}
};
Node * head;
Node * tail;
void InsertBefore(Node * curr, int data)
{
Node * newNode = new Node(data, curr->next);
curr->next = newNode;
std::swap(curr->data, newNode->data);
}
int Size(Node * head)
{
Node * curr;
curr = head;
int size = 1;
while (curr != tail)
{
size++;
curr = curr->next;
}
return size;
}
void Reverse(Node * &head, Node * &tail) {
std::cout<<"!!!"<<std::endl;
std::cout<<head<<std::endl;
std::cout<<head->data<<std::endl;
std::cout<<head->next<<std::endl;
std::cout<<&head<<std::endl;
//std::cout<<type(*&head)<<std::endl;
std::cout<<"!!!"<<std::endl;
Node * prevNode = head;
Node * rotateNode = head->next;
head->next = NULL;
while (rotateNode) {
Node *next = rotateNode->next;
rotateNode->next = prevNode;
prevNode = rotateNode;
rotateNode = next;
}
std::swap(head, tail);
}
int main()
{
head = new Node(1, nullptr);
tail = head;
InsertBefore(head, 3);
tail = tail->next;
InsertBefore(head, 99);
InsertBefore(head, 13232);
InsertBefore(head, 2333);
InsertBefore(head, 121);
std::cout<<"Before Reverse"<<std::endl;
Node * ptr = head;
while (ptr)
{
std::cout<<ptr->data<<std::endl;
ptr = ptr->next;
}
// std::cout<<head->data<<'?'<<head->next->data<<std::endl;
// std::cout<<tail->data<<std::endl;
Reverse(head, tail);
// std::cout<<head->data<<'?'<<head->next->data<<std::endl;
std::cout<<"After Reverse"<<std::endl;
ptr = head;
while (ptr)
{
std::cout<<ptr->data<<std::endl;
ptr = ptr->next;
}
std::cout<<Size(head)<<std::endl;
return 0;
}
// int main()
// {
// int a = 1;
// int b = 2;
// std::swap(a, b);
// printf("%d, %d\n", a, b);
// }