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)//败给你了,不是!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 };
不带头结点的单链表反转
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)//败给你了,不是!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 };