http://blog.csdn.net/lfeng_coding/article/details/47300563
題目描述:在已知單鏈表頭節點的情況下,設計算法逆置單鏈表并輸出
方法一:采用首先將頭節點指向空,讓其變為尾節點,然后利用中間節點 p、q 將其后的節點一個接一個改為指向前面的節點

/****************************
*作者:劉峰
* 時間:2015\8\5
* 環境:VS2013
* 功能:實現創建一個節點可控的單鏈,并逆置輸出
****************************/
- #include?"stdafx.h"??
- ??
- #include?<iostream>??
- using?namespace?std;??
- ??
- struct?List??
- {??
- ????int?num;??
- ????List?*next;??
- };??
- ??
- List?*createList(int?n)?????????
- {??
- ????List?*head,?*p,?*q;??
- ????q=head?=?NULL;?????
- ????int?i;??
- ????for?(i?=?n;?i?>?0;?--i)??
- ????{??
- ????????p?=?new?List;???????
- ????????cin?>>?p->num;????????
- ????????if?(head?==?NULL)??
- ????????{??
- ????????????head?=?p;??
- ????????}??
- ????????else??
- ????????{??
- ????????????q->next?=?p;??
- ????????}??
- ????????q?=?p;??
- ????}??
- ????q->next?=?NULL;??
- ????return?head;??
- }??
- ??
- List?*ReverseList(List?*head)????????????
- {??
- ????List?*p,?*r;?????????
- ????if?(head->next?==?NULL)??
- ????????return?head;??
- ????p?=?head;????????????
- ????r?=?p->next;?????????
- ????p->next?=?NULL;??????
- ????while?(r)??
- ????{??
- ????????p?=?r;??
- ????????r?=?r->next;??
- ????????p?->next?=?head;?????
- ????????head?=?p;????????????
- ????}??
- ????return?head;??
- }??
- ??
- void?print(List?*head)??????????
- {??
- ????List?*p;??
- ????p?=?head;??
- ????while?(p)??
- ????{??
- ????????cout<<p->num;??
- ????????p?=?p->next;??
- ????????cout?<<?"?";??
- ????}??
- ????cout?<<?endl;??
- }??
- int?_tmain(int?argc,?_TCHAR*?argv[])??
- {??
- ????List?*p,?*q;??
- ????cout?<<?"請輸入單鏈表的節點個數:";??
- ????int?n;??
- ????cin?>>?n;??
- ????cout?<<?endl;??
- ????cout?<<?"創建一個節點為"?<<?n?<<?"的單鏈表"?<<?endl;??
- ????p?=?createList(n);??
- ????cout?<<?endl;??
- ????cout?<<?"這步為程序逆置單鏈表"?<<?endl;??
- ????q?=?ReverseList(p);??
- ????cout?<<?endl;??
- ????cout?<<?"打印逆置后的單鏈表"?<<?endl;??
- ????print(q);??
- ????cout?<<?endl;??
- ????return?0;??
- }??
方法二:用p,q指向單鏈表中相鄰的兩節點,將r指向q的下一個結點,然后同步后移。當q=NULL時,表示指向原單鏈表的尾結點,將p賦值為頭節點 head 即可。
逆置函數代碼如下(其他部分不變):
List *ReverseList(List *head)
{
List *p, *q, *r;
p = head;
if (p->next == NULL)
return head;
q = p->next;
while (q != NULL) ? ? //q為空,說明p為最后一個節點,所以結束while后將q賦值給head,作為逆置后的表頭
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head->next = NULL; ? //將原head變為逆置后鏈表的表尾
head = p; ? ? ? ? ? ?//逆置后新的表頭
return head;
}