题目:Reverse a singly linked list.(反转单链表)
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?(使用递归和迭代方法求解)
递归法(从后往前):
用递归的方法比较直观,可以实现从后往前反转。需要注意的是反转之后的头结点是原来的最后一个节点,递归的时候需要将它记录下来。
// An highlighted block
class Solution {
private: ListNode* first;
ListNode* reverse(ListNode* head)
{
if(head->next==NULL)
{
first = head;
return head;
}
ListNode* secondList = reverse(head->next);
secondList->next = head;
head->next = NULL;
return head;
}
public:
ListNode* reverseList(ListNode* head)
{
if(!head) return NULL;
reverse(head);
return first;
}
};
迭代法(从前往后迭代):
从前面的节点开始反转,可以将第一个节点前面加一个辅助的NULL节点,程序的主角就是三个前后相连指针pre, cur, nex, 每次迭代需要反转pre 和 cur, 而nex是为了将反转之前的cur的下一个节点记录下来,用于更新cur指针.
// An highlighted block
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
ListNode* pre = NULL;
ListNode* cur = head;
while(cur)
{
ListNode* nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
return pre;
}
};