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

Reverse Linked List

时间:2015-06-07 21:25:26      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 class Solution {
 2 public:
 3     ListNode* reverseList(ListNode* head) {
 4         if(head==NULL)
 5             return head;
 6         ListNode* pre=head;
 7         ListNode* mid=head->next;
 8         ListNode* tail;
 9         head->next=NULL;
10         while(mid!=NULL)
11         {
12             tail=mid->next;
13             mid->next=pre;
14             pre=mid;
15             mid=tail;
16         }
17         return pre;
18     }
19 };
View Code

考虑链表为空的情况,解决方法可以是迭代改变每个节点的next指针

 

完整代码:

技术分享
 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <algorithm>
 5 #include <map>
 6 using namespace std;
 7 typedef struct ListNode {
 8     int val;
 9     ListNode *next;
10     ListNode(int x) : val(x), next(NULL) {}
11 }ListNode;
12 class Solution {
13 public:
14     ListNode* reverseList(ListNode* head) {
15         if(head==NULL)
16             return head;
17         ListNode* pre=head;
18         ListNode* mid=head->next;
19         ListNode* tail;
20         head->next=NULL;
21         while(mid!=NULL)
22         {
23             tail=mid->next;
24             mid->next=pre;
25             pre=mid;
26             mid=tail;
27         }
28         return pre;
29     }
30 };
31 ListNode* ListInsert(int d)
32 {
33     ListNode* cur=NULL;
34     cur=(ListNode*)malloc(sizeof(ListNode));
35     cur->val=d;
36     cur->next=NULL;
37     return cur;
38 }
39 int main()
40 {
41     int n;
42     while(cin>>n)
43     {
44         Solution sol;
45         int i,d;
46         ListNode *head=NULL,*tail=NULL,*cur;
47         tail=(ListNode*)malloc(sizeof(ListNode));
48         for(i=0;i<n;i++)
49         {
50             cin>>d;
51             cur=ListInsert(d);
52             if(i==0)
53             {
54                 head=cur;
55                 tail=cur;
56             }
57             else
58             {
59                 tail->next=cur;
60                 tail=cur;
61             }
62         }
63         ListNode* h=sol.reverseList(head);
64         while(h!=NULL)
65         {
66             cout<<h->val<<" ";
67             h=h->next;
68         }
69         cout<<endl;
70     }
71     return 0;
72 }
View Code

1、定义节点指针,使用前需要malloc分配内存?

指针在使用时需要指向一块内存,不使用则可以指向任何地方

2 、55行tail=cur;  若直接在46行初始化tail=head, 删去55行代码,head不能自动连接到下一个节点?

 因为在为tail分配内存后tail不再指向head,所以删去55行代码,head不能自动连接到下一个节点

Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/varcom/p/4559058.html

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