LeetCode #206

来源:互联网 发布:淘宝网购物女装t恤 编辑:程序博客网 时间:2024/04/25 14:21

题目描述:

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

实现链表的翻转,而且题目提示可以尝试迭代和递归两种方法。

算法思路参考:http://www.cnblogs.com/grandyang/p/4478820.html

迭代的方法比较容易想到,不过指针的操作略微复杂需要比较小心。先定义result节点,将其置于head节点之前,然后每次都把head之后的节点插入到result之后,直到head->next为空,即head为最后一个节点,迭代结束。由于需要保证将head->next移动至result之后,那么head->next显然不能为空,所以节点数为0或者1的情况需要预先排除。

class Solution {public:    ListNode* reverseList(ListNode* head) {        if(head==NULL) return NULL;        else if(head->next==NULL) return head;                ListNode* result=new ListNode(0);        result->next=head;        while(head->next!=NULL)        {            ListNode* p=head->next;            ListNode* q=head->next->next;            ListNode* temp=result->next;            result->next=p;            p->next=temp;            head->next=q;        }        return result->next;    }};


还可以采用递归的方法,即用递归求得第一个节点后面的所有节点的翻转结果,再把这第一个节点插入其余节点翻转后的链表中。而且由于在递归过程中,p->next变为reverseList(p->next)的最后一位,所以可以直接把p置于p->next之后,再返回head即可。

class Solution {public:    ListNode* reverseList(ListNode* head) {        if(head==NULL) return NULL;        else if(head->next==NULL) return head;         else if(head->next!=NULL)        {            ListNode* p=head;            head=reverseList(p->next);            p->next->next=p;            p->next=NULL;        }        return head;    }};

原创粉丝点击