码迷,mamicode.com
首页 > 编程语言 > 详细

C++单链表反转

时间:2015-04-07 13:22:27      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

单链表反转笔记:

 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 }

 

C++单链表反转

标签:

原文地址:http://www.cnblogs.com/90zeng/p/cpp_reverse_list.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!