1 struct linka {
2 int data;
3 linka* next;
4 };
5 void reverse(linka*& head) {
6 if(head ==NULL)
7 return;
8 linka *pre, *cur, *ne;
9 pre=head;
10 cur=head->next;
11 while(cur)
12 {
13 ne = cur->next;
14 cur->next = pre;
15 pre = cur;
16 cur = ne;
17 }
18 head->next = NULL;
19 head = pre;
20 }
其中比較難理解的是linka*& head,傳入的其實(shí)就是linka *的類型就可以了,linka *是表示linka類型的指針,&表示head的地址,也就是linka的指針
另外需要熟悉的是head->next,其實(shí)有點(diǎn)像C#中的head.Next,就是structure中的一個(gè)屬性.
首先定義3個(gè)指針,分別是前中后,然后當(dāng)中間那個(gè)指針非空,就是當(dāng)前不是空,就做循環(huán)里的事情
注意的是這個(gè)算法里面next是在循環(huán)里面賦值的
每次循環(huán)都把current指向previous了,然后大家都往后移一個(gè),next=current->next必須在current改變方向之前做,否則改變了方向之后current的next就變成previous了。
最后跳出循環(huán)之后,將header的next首先置空,因?yàn)閔ead變成了最后一個(gè)node了。然后head就變成了previous,因?yàn)楫?dāng)時(shí) current和next都為NULL了,只有previous為最后一個(gè)節(jié)點(diǎn)(或者說這時(shí)候應(yīng)該是第一個(gè)非空節(jié)點(diǎn),也就是head)
終于把整個(gè)算法理解了一遍,最后想想其實(shí)挺簡(jiǎn)單,但是能用c++寫出來也不太容易,特別是在面試的時(shí)候。
再增加一個(gè)遞歸的單鏈表反轉(zhuǎn)的方法:
1 static link ReverseLink3(link pNode) // using recursion
2 {
3 if (pNode.next == null)
4 return pNode;
5 link pNext = pNode.next;
6 link head = ReverseLink3(pNext);
7 pNext.next = pNode;
8 pNode.next = null;
9 return head;
10 }