码迷,mamicode.com
首页 > 其他好文 > 详细

给定一个链表的头指针,要求只遍历一次,将单链表中的元素顺序反转过来

时间:2014-09-01 19:10:03      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   for   div   代码   log   

经典题目,代码如下:

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 struct ListNode {
 5     int m_iData;
 6     ListNode* m_pNext;
 7 };
 8 ListNode* Reverse(ListNode* in_pListNode) {
 9     if(in_pListNode == NULL) {
10         return NULL;
11     }else if(in_pListNode->m_pNext == NULL) {
12         return in_pListNode;
13     }
14     ListNode* t_pFirst = in_pListNode->m_pNext;
15     ListNode* t_pSecond = in_pListNode->m_pNext->m_pNext;
16     in_pListNode->m_pNext = NULL;
17     while(t_pFirst != NULL && t_pSecond != NULL) {
18         t_pFirst->m_pNext = in_pListNode;
19         in_pListNode = t_pFirst;
20         t_pFirst = t_pSecond;
21         t_pSecond = t_pSecond->m_pNext;
22     }
23     t_pFirst->m_pNext = in_pListNode;
24     return t_pFirst;
25 }
26 
27 int main() {
28     ListNode* t_iListNode = new ListNode();
29     ListNode* t_iListNodeHead = t_iListNode;
30     for(int i = 1; i < 10; i ++) {
31         t_iListNode->m_iData = i;
32         ListNode* t_iListNodeNext = new ListNode();
33         t_iListNode->m_pNext = t_iListNodeNext;
34         t_iListNode = t_iListNodeNext;
35     }
36     t_iListNode->m_iData = 10;
37     ListNode* t_iTempListNode =t_iListNodeHead;
38     cout << "链表翻转前:" ;
39     while(t_iTempListNode != NULL) {
40         cout << t_iTempListNode->m_iData << " ";
41         t_iTempListNode = t_iTempListNode->m_pNext;
42     }
43     cout << endl;
44     
45     t_iTempListNode = Reverse(t_iListNodeHead);
46     
47     cout << "链表翻转后:" ;
48     while(t_iTempListNode != NULL) {
49         cout << t_iTempListNode->m_iData << " ";
50         t_iTempListNode = t_iTempListNode->m_pNext;
51     }
52     cout << endl;
53       system("pause"); 
54       return 0;
55      
56      
57 }

 

给定一个链表的头指针,要求只遍历一次,将单链表中的元素顺序反转过来

标签:style   blog   color   os   io   for   div   代码   log   

原文地址:http://www.cnblogs.com/xxiaoye/p/3949656.html

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