生活随笔
收集整理的這篇文章主要介紹了
用C++实现单链表的创建、逆置和输出 的两种方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
http://blog.csdn.net/lfeng_coding/article/details/47300563
題目描述:在已知單鏈表頭節(jié)點(diǎn)的情況下,設(shè)計(jì)算法逆置單鏈表并輸出
方法一:采用首先將頭節(jié)點(diǎn)指向空,讓其變?yōu)槲补?jié)點(diǎn),然后利用中間節(jié)點(diǎn) p、q 將其后的節(jié)點(diǎn)一個(gè)接一個(gè)改為指向前面的節(jié)點(diǎn)
/****************************
*作者:劉峰
* 時(shí)間:2015\8\5
* 環(huán)境:VS2013
* 功能:實(shí)現(xiàn)創(chuàng)建一個(gè)節(jié)點(diǎn)可控的單鏈,并逆置輸出
****************************/
[cpp]?view plain
?copy #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?<<?"請輸入單鏈表的節(jié)點(diǎn)個(gè)數(shù):";?? ????int?n;?? ????cin?>>?n;?? ????cout?<<?endl;?? ????cout?<<?"創(chuàng)建一個(gè)節(jié)點(diǎn)為"?<<?n?<<?"的單鏈表"?<<?endl;?? ????p?=?createList(n);?? ????cout?<<?endl;?? ????cout?<<?"這步為程序逆置單鏈表"?<<?endl;?? ????q?=?ReverseList(p);?? ????cout?<<?endl;?? ????cout?<<?"打印逆置后的單鏈表"?<<?endl;?? ????print(q);?? ????cout?<<?endl;?? ????return?0;?? }??
方法二:用p,q指向單鏈表中相鄰的兩節(jié)點(diǎn),將r指向q的下一個(gè)結(jié)點(diǎn),然后同步后移。當(dāng)q=NULL時(shí),表示指向原單鏈表的尾結(jié)點(diǎn),將p賦值為頭節(jié)點(diǎn) head 即可。
逆置函數(shù)代碼如下(其他部分不變):
List *ReverseList(List *head)
{
List *p, *q, *r;
p = head;
if (p->next == NULL)
return head;
q = p->next;
while (q != NULL) ? ? //q為空,說明p為最后一個(gè)節(jié)點(diǎn),所以結(jié)束while后將q賦值給head,作為逆置后的表頭
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head->next = NULL; ? //將原h(huán)ead變?yōu)槟嬷煤箧湵淼谋砦?br style="" /> head = p; ? ? ? ? ? ?//逆置后新的表頭
return head;
}
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)
總結(jié)
以上是生活随笔為你收集整理的用C++实现单链表的创建、逆置和输出 的两种方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。