日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++中链表反转2

發(fā)布時(shí)間:2024/9/27 c/c++ 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++中链表反转2 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

引言

周期按我也寫過類似鏈表反轉(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é)

以上是生活随笔為你收集整理的C++中链表反转2的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。