您的位置:首页 > 其它

LeetCode 刷题 -- 反转一个单链表

2015-11-13 16:07 267 查看
Reverse a singly linked list.

非递归法实现:

/**
* 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 *pre, *next;
ListNode *it = head;
pre = NULL;

while(it)
{
next = it->next;
it->next = pre;
pre = it;
it = next;
}

return pre;
}
};

递归实现:

Youtube上有个视频对递归实现讲得不错:
https://www.youtube.com/watch?v=MRe3UsRadKw
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next == NULL)
{
return head;
}

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