您的位置:首页 > 其它

206. Reverse Linked List(递归法问题)

2018-02-07 16:06 155 查看

问题描述

Reverse a singly linked list.

Hint:

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

题目链接:

思路分析

将一个链表翻转。用递归和迭代两种方式。

迭代法:使用三个指针,分别为head,head之前的结点pre,head之后的结点post。在至少有两个节点的情况下,开始循环。

改变head的next到pre,然后向前推进,pre = head;head = post; post = post.next。最后返回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;
ListNode* pre = NULL;
ListNode* post = head->next;
while(post != NULL){
head->next = pre;
pre = head;
head = post;
post = post->next;
}
head->next = pre;
return head;

}
};


时间复杂度:O(n)

空间复杂度:O(1)

反思

链表题一直是自己的弱项。也没能实现递归翻转的方法,只能用最直观的方式解决。

来自Discussion区的代码:

迭代:

更加简单,用tmp代替了我的post,用来储存原来的head的下一个node。

/**
* 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) {
ListNode *previous = NULL, *current=head, *tmp;
while(current){
tmp = current->next;
current->next = previous;
previous = current;
current = tmp;
}
return previous;
}
};


递归:

使用了auto关键字,可以在生命变量的时候根据变量的初始值类型自动匹配类型。

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