C++实现单链表的反序
生活随笔
收集整理的這篇文章主要介紹了
C++实现单链表的反序
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
引言
將一個沒有空結(jié)點作為頭的單鏈表實現(xiàn)反轉(zhuǎn)。其實質(zhì)就是將結(jié)點的指針域指向反轉(zhuǎn)。定義指向當前結(jié)點的指針,指向前一個結(jié)點的指針,指向當前結(jié)點的后一個結(jié)點的指針,這個過程中包含只有一個結(jié)點的單鏈表,那么反轉(zhuǎn)之后還是它本身,只有兩個結(jié)點的單鏈表,反轉(zhuǎn)之后由第一個結(jié)點的指針指向第二個結(jié)點,第二個結(jié)點的指針域指向為空,變?yōu)榈诙€結(jié)點的指針指向第一個結(jié)點,第一個結(jié)點的指針域為空。當結(jié)點數(shù)大于二,便就是一系列結(jié)點指針指向的反轉(zhuǎn),最后記得將反轉(zhuǎn)后的單鏈表的尾結(jié)點的指針指向空。
示例
下面是在vs2010上實現(xiàn)的單鏈表反序。
// reverseList.cpp : 定義控制臺應用程序的入口點。 //#include "stdafx.h" #include <stdlib.h> #include <iostream> using namespace std;/*********************** 功能:實現(xiàn)無頭單鏈表的反序 包含的功能函數(shù): struct Node* createList(int n,int data) 創(chuàng)建n的結(jié)點的單鏈表,鏈表采用data++的形式增減每一個結(jié)點的值 struct Node* reverseList(struct Node **pList) 將但聯(lián)編反序,大致的形式類似:1-》2-》3 反序后3-》2-》1 void printList(struct Node *pList) 輸出;鏈表pList的結(jié)點元素 **********************/struct Node {int num;struct Node *next; };struct Node* createList(int n,int data) {struct Node *ph = NULL;struct Node *pnow = NULL;struct Node *pLast = NULL;while (n >= 0){struct Node *pNode = new struct Node;pNode->next = NULL;pNode->num = data++;if(ph == NULL){ph = pNode;}pnow = pNode;if(pLast != NULL){pLast->next = pnow;}pLast = pnow;--n;}return ph;}struct Node* reverseList(struct Node **pList) {struct Node *pre = *pList;//指向前一個結(jié)點struct Node *pCur = NULL;//指向當前結(jié)點struct Node *pNext = NULL;//指向當前結(jié)點的下一個結(jié)點if(pre->next != NULL){pCur = pre->next;if(pCur->next != NULL)//結(jié)點數(shù)最少為3個{pNext = pCur->next;pre->next = NULL;while(pCur){pCur->next = pre;if(pNext){pre = pCur;pCur = pNext;pNext = pNext->next;}else{break;}}return pCur;}else//只有兩個結(jié)點{pCur->next = pre;pre->next = NULL;return pCur;}}else//只有一個結(jié)點{return pre;} }void printList(struct Node *pList) {struct Node *ph = pList;while(ph != NULL)//注意這里是結(jié)點不為空ph != NULL,不是結(jié)點的指針指向不為空ph->next != NULL{cout<<ph->num<<"\t";ph = ph->next;}cout<<endl; }int _tmain(int argc, _TCHAR* argv[]) {struct Node *pList = createList(4,1);printList(pList);cout<<"================="<<endl;struct Node * ph = reverseList(&pList);printList(ph);system("pause");return 0; }程序的運行效果如下:
僅以記錄。
總結(jié)
以上是生活随笔為你收集整理的C++实现单链表的反序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql event 变量_mysql
- 下一篇: c++文件流读取一行_「软帝学院」Jav