206. Reverse Linked List
解析
逆转链表,基本功。如果你是刚学习链表,每次写这类题的时候,都把链表在纸上画出来,是最好的方法.
没有dummy节点:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL ||head->next ==NULL)
return head;
ListNode* p = head;
ListNode* q = head->next;
head->next = NULL;
ListNode* t;
while(q->next !=NULL){
t = q->next;
q->next = p;
p = q;
q = t;
}
q->next =p;
return q;
}
};
有dummy节点
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL)
return NULL;
ListNode dummy(-1);
dummy.next = head;
ListNode* p = &dummy;
ListNode* q = dummy.next;
ListNode* t;
while(q->next !=NULL){
t = q->next;
q->next = p;
p = q;
q = t;
}
q->next = p;
head->next = NULL;
return q;
}
};
递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev =NULL;
helper(NULL,head,&prev);
return prev;
}
void helper(ListNode* pre,ListNode* cur,ListNode** head){
if(cur == NULL)
*head = pre;
else{
helper(cur,cur->next,head);
cur->next = pre;
}
}
};