Interview question 20: How to reverse a single linked list
(1) Reverse a linked list. Circular Algorithm
Linked list is a basic and commonly used data structure in C. This thing must be mastered proficiently. Reversing a linked list is more troublesome than ordering it. The key is to abstract three things: the previous node, the current node, and the next node
. When a node
has these three things, the algorithm can be performed.
These three things can be understood as data structures, and the other steps are loops and algorithms.
126 //反转一个链表
127 Link* LinkRevert(Link* p){
128 printf("enter function LinkRevert\n");
129 if(p->next == NULL){
130 return p;
131 }
132 Link* pre = p->next;
133 Link* cur = pre->next;
134 Link* behind = cur->next;
135 pre->next = NULL;
136 printf("cur1=%p\n", cur);
137 while(cur)
138 {
139 printf("cur2=%p\n", cur);
140 cur->next = pre;
141 pre = cur;
142 cur = behind;
143 if(behind)
144 {
145 behind = behind->next;
146 }
147 }
148 p->next = pre;
149 printf("cur3=%p\n", pre);
150 printf("exit function LinkRevert\n");
151 return p;
152 }
153 int main() {
154 Link* p = initLink();
155 printf("初始化链表为:\n");
156 display(p);
157 Link* p2 = LinkRevert(p);
158 display(p2);
159 Link_free(p2);
160 return 0;
161 }
Operation status:
root@mkx:~/learn/link# ./link
初始化链表为:
enter function displaty
1 2 3 4
exit function displaty
enter function LinkRevert
cur1=0x22a6050
cur2=0x22a6050
cur2=0x22a6070
cur2=0x22a6090
cur3=0x22a6090
exit function LinkRevert
enter function displaty
4 3 2 1
exit function displaty
root@mkx:~/learn/link#