#206. Reverse Linked List
题目来源:
https://leetcode.com/problems/reverse-linked-list/description/
题意分析:
reverse一个单向链表,用迭代跟递归两种方式。
例子:
代码:
递归方式
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head==NULL)
return NULL;
return help(head,head);
}
ListNode* help(ListNode* before, ListNode* now){
if (now->next==NULL){
now->next=before;
before->next=NULL;
return now;
}
else{
ListNode* new_head=help(now,now->next);
now->next=before;
before->next=NULL;
return new_head;
}
}
};
迭代方式
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head==NULL)
return NULL;
ListNode* trace=head;
ListNode* tail=head->next;
head->next=NULL; //记得把头指针的next设为NULL,否则会陷入死循环
while (tail!=0){
trace=tail;
tail=tail->next;
trace->next=head;
head=trace;
}
return head;
}
};