您的位置:首页 > 其它

LeetCode.206. Reverse Linked List(反转有序链表)

2017-06-27 16:27 465 查看
实习面试了三次,两次问道这个题目,有必要整理一下了。

Reverse
a singly linked list.

#方法一:
使用迭代的方法,算法时间复杂度是O(n),
空间复杂度为O(1)
/**
* 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;
else
{
ListNode* p = head;
ListNode* t = NULL;
ListNode* h = NULL;
while(p != NULL)
{
h = p -> next;
p -> next = t;
t = p;
p = h;
}
head = t;
}
return head;
}
};


#方法二
使用递归
/**
* 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;
else
{
ListNode* newhead = reverseList(head -> next);
head -> next -> next = head;
head -> next = NULL
}
}
};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: