反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
解法1:迭代
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL)//不需要反转的情况
{
return head;
}
ListNode *p=head;//遍历节点的上一个节点
ListNode *k=p->next;//当前遍历节点
head->next=NULL;//更改头
while(k)
{
ListNode *temp=k->next;//临时节点保存下一个遍历节点
k->next=p;
p=k;
k=temp;
}
head=p;
return head;
}
};
解法2:递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode *new_head = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return new_head;
}
};
如何理解:递归理解