您的位置:首页 > 其它

#leetcode#206. Reverse Linked List

2016-04-19 23:09 274 查看
单链表翻转(递归和迭代两种)

迭代

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next==NULL)
return head;
ListNode Result(0);
ListNode *p=head;
while(p)
{
ListNode *q=p->next;
p->next=Result.next;
Result.next=p;
p=q;
}
return Result.next;
}
};

递归

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL) return NULL;
if(head->next==NULL) return head;

ListNode *p=head->next;
ListNode *n=reverseList(p);

head->next=NULL;
p->next=head;
return n;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: