C++中链表反转2
引言
周期按我也寫過類似鏈表反轉(zhuǎn)的文章,這個(gè)鏈表反轉(zhuǎn)是在第二次寫的時(shí)候?qū)懙?#xff0c;由于都是靠當(dāng)時(shí)的思路,兩個(gè)在代碼實(shí)現(xiàn)上有所差異,僅以記錄。
示例
編程環(huán)境
在vs2010下編寫的C++控制臺輸出程序,文件名由main.cpp改為testReverseList2.cpp,其它默認(rèn)生成。
代碼實(shí)現(xiàn)
下面是testReverseList2.cpp中的代碼實(shí)現(xiàn)。
// testReverseList2.cpp : 定義控制臺應(yīng)用程序的入口點(diǎn)。 //#include "stdafx.h" #include <iostream> #include <vector> #include <stdlib.h>using namespace std;/************************************************************************/ /* 功能: stuList *reverseList(stuList *ph) 將鏈表反轉(zhuǎn),返回指向反轉(zhuǎn)后的鏈表 stuList * createList(vector<int> &nVec) 創(chuàng)建鏈表,返回創(chuàng)建的鏈表 void outPut(vector<int> &vec) 輸出動態(tài)數(shù)組中的元素 void fromControlGetNum(vector<int> &nVec) 控制臺輸入數(shù)值,存入到動態(tài)數(shù)組中,直到輸入回車鍵停止輸入 void outPutList(stuList *ph) 輸出鏈表中結(jié)點(diǎn)的值*/ /************************************************************************/struct stuList{int data;stuList *pNext; };stuList * createList(vector<int> &nVec){int nSize = nVec.size();int i = 0;stuList *ph,*pPre,*pCur;while (i < nSize){pCur = new stuList;if (pCur){pCur->data = nVec[i];pCur->pNext = nullptr;if(i == 0){ph = pCur;pPre = pCur;}else{pPre->pNext = pCur;pPre = pCur;}++i;}}return ph; }stuList *reverseList(stuList *ph){stuList *pCur,*pPre,*pFont;int i= 0;pPre = ph;pCur = ph->pNext;if(pCur->pNext != nullptr){//3個(gè)或者3個(gè)以上結(jié)點(diǎn)pFont = pCur->pNext;while (pFont != nullptr){if(i == 0){pPre->pNext = nullptr;}pCur->pNext = pPre;pPre = pCur;pCur = pFont;if (pFont->pNext != nullptr){pFont = pFont->pNext;} else{pCur->pNext = pPre;break;}++i;}}else{//只有2個(gè)結(jié)點(diǎn)pPre->pNext = nullptr;pCur->pNext = pPre;}return pCur; }void outPut(vector<int> &vec){for (int i = 0; i < vec.size(); ++i){cout<<vec[i]<<"\t";}cout<<endl; }void fromControlGetNum(vector<int> &nVec){int num;cout<<"請輸入創(chuàng)建鏈表的值:"<<endl;do {cin>>num;nVec.push_back(num);} while (cin.get() != '\n');//當(dāng)輸入回車的時(shí)候,停止輸入,但是前一個(gè)為空格再回車就不能結(jié)束輸入 }void outPutList(stuList *ph){while (ph != nullptr){cout<<ph->data<<"\t";ph = ph->pNext;}cout<<endl; }int _tmain(int argc, _TCHAR* argv[]) {vector<int> nVec;fromControlGetNum(nVec);cout<<"輸入的數(shù)組輸出如下:"<<endl;outPut(nVec);stuList * phList = createList(nVec);cout<<"鏈表輸出如下:"<<endl;outPutList(phList);stuList *pReList = reverseList(phList);cout<<"鏈表反轉(zhuǎn)后輸出如下:"<<endl;outPutList(pReList);system("pause");return 0; }運(yùn)行結(jié)果
創(chuàng)建2個(gè)結(jié)點(diǎn)的鏈表輸出結(jié)果:
輸入3個(gè)或者多于3個(gè)結(jié)點(diǎn)的鏈表的輸出結(jié)果:
總結(jié)
- 上一篇: linux中ssh启动报错,Linux(
- 下一篇: c++实现引用计数