Fork me on GitHub

[leetcode-206-Reverse Linked List]

Reverse a singly linked list.

两种办法:

1.头插法。

2.递归。

ListNode* reverseList(ListNode* head)
{
    if(head == NULL) return head;
    ListNode* dumb = new ListNode(0);
    dumb->next = head;
    ListNode * p = head->next;
    head->next = NULL;
    while(p != NULL)
    {
        head = p;
        p = p->next;
        head->next = dumb->next;
        dumb->next = head;
    }
    return dumb->next;
}
//递归方法
ListNode* reverseList2(ListNode* head)
{
    if(head == NULL || head->next == NULL) return head;

    ListNode * p = head->next;
    head->next = NULL;
    ListNode* newhead = reverseList2(p);
    p->next = head;

    return newhead;
}

参考:

https://discuss.leetcode.com/topic/13317/accepted-c-solutions-both-iteratively-and-recursively

posted @ 2017-04-08 14:44  hellowOOOrld  阅读(161)  评论(0编辑  收藏  举报