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

No.206 Reverse Linked List

时间:2015-05-25 16:29:37      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

No.206 Reverse Linked List

Reverse a singly linked list.

单链表带头结点【leetcode判错】:

 1 #include "stdafx.h"
 2 
 3 struct ListNode
 4 {
 5     int val;
 6     ListNode *next;
 7     ListNode(int x):val(x),next(NULL){}
 8 };
 9 class Solution
10 {
11 public:
12     ListNode* reverseList(ListNode* head)
13     {//单链表反转
14      //带头结点的单链表:head里面存放链表长度(或其他信息),head->next指向第一个实际节点;
15         if(!(head) || !(head->next))//如果head为空,或者头结点指向空节点(链表长度为0)
16             return head;
17 
18         ListNode *current = head->next;
19         ListNode *back = NULL;//逆转之后,头结点变为尾节点,其next为Null  
20         ListNode *front;
21         //current 记录当前位置,back记录上一个位置,为current->next的值;front记录下一个位置,反转后current不等于current->next  
22         while(!current)
23         {
24             front = current->next;//反转后不能再用current->next,所以先记录下这个节点  
25             current->next = back;
26             back = current;
27             current = front;
28         }
29         head->next = back; //current已经为空,所以back为尾节点。head->next指向它。
30         return head;
31     }
32 };

 

不带头结点的单链表反转【感觉没问题,但leetcode判错】:

Input:[1,2]

Output:[]

Expected:[2,1]

 1 class Solution
 2 {
 3 public:
 4     ListNode* reverseList(ListNode* head)
 5     {//单链表反转
 6      //不带头结点的单链表
 7         if(!(head) || !(head->next))
 8             return head;
 9 
10 //改:    ListNode *current = head->next;
11         ListNode *current = head;
12         ListNode *back = NULL;
13         ListNode *front;
14 
15         while(!current)
16         {
17             front = current->next;
18             current->next = back;
19             back = current;
20             current = front;
21         }
22 //改:    head->next = back;
23         head = back;
24         return head;
25     }
26 };

 

No.206 Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/dreamrun/p/4528008.html

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