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