程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++單鏈表反轉,單鏈表反轉

C++單鏈表反轉,單鏈表反轉

編輯:C++入門知識

C++單鏈表反轉,單鏈表反轉


單鏈表反轉筆記:

 1 #include<iostream>
 2 #include<string.h>
 3 using namespace std;
 4 
 5 struct ListNode
 6 {
 7     int val;
 8     ListNode* next;
 9     ListNode(int i):val(i),next(NULL){};
10 };
11 void printList(ListNode* myList)
12 {
13     while(myList != NULL)
14     {
15         cout << myList -> val << "->";
16         myList = myList -> next;
17     }
18     cout << "NULL" << endl;
19 }
20 ListNode* reverseList(ListNode* pHead)
21 {
22 
23     if(pHead == NULL) return pHead;
24     ListNode* pre = NULL;
25     ListNode* cur = pHead;
26     while(cur != NULL)
27     {
28        ListNode* newpre = cur;
29        ListNode* newcur = cur -> next;
30        cur -> next = pre;
31        cur = newcur;
32        pre = newpre;
33     }
34     return pre;
35 }
36 int main()
37 {
38     ListNode* pHead =  new ListNode(0);
39     ListNode* cur = pHead;
40     for (int i = 1; i < 10; ++i)
41     {
42         ListNode* newNode = new ListNode(i);
43         cur -> next = newNode;
44         cur = cur -> next;
45     }
46     printList(pHead);
47     printList(reverseList(pHead));
48     return 0;
49 }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved