您的位置:首页 > 其它

leetcode-206-Reverse Linked List

2017-01-20 20:13 260 查看

问题

题目:[leetcode-206]

思路

递归的时候注意:

头结点的保存时机(边界条件时做的)

每次head->next = NULL;不要忘了修改

代码(递归)

/**
* 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)
return NULL;

ListNode* ret = NULL;
if(head->next)
{
ret = reverseList(head->next);
head->next->next = head;
head->next = NULL;
}
else
return head;

return ret;
}
};


思路1

当然,头插法也可以。没必要节点复制,直接改指针也可以。当然,这个角度说也有点像就地置逆。

代码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) return NULL;
ListNode* ret = NULL;
while(head){
ListNode* nex = head->next;
if(!ret)
{
ret = head;
ret->next = NULL;
}
else
{
head->next = ret;
ret = head;
}
head = nex;
}
return ret;
}
};


思路2

就地置逆。

代码2(就地置逆)

/**
* 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)
return NULL;

ListNode* ret = NULL;
while(head)
{
ListNode* nex = head->next;
head->next = ret;
ret = head;

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