Reverse a singly linked list.

Hint:

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

反向链表,分别用递归和迭代方式实现。

递归Iteration:

新建一个node(value=任意值, next = None), 用一个变量 next 记录head.next,head.next指向新node.next,新 node.next 指向head,next 进入下一个循环,重复操作,直到结束。

迭代Recursion:

假设有链表1 -> 2 -> 3 -> 4 -> 5要进行反转,第一层先把1 -> 2 -> 3 -> 4 -> 5和None传入递归函数(head, newhead),先记录head的next(2 -> 3 -> 4 -> 5),head(1)指向newhead(None)变成(1->None),然后把(2 -> 3 -> 4 -> 5,  1 -> None)递归传入下一层,记录head的next(3 -> 4 -> 5),head(2)指向newhead(1->None)变成(2 -> 1->None),然后把(3 -> 4 -> 5,  2 -> 1 -> None)递归传入下一层,直到最后head=None时返回newhead,此时 newhead = 5 -> 4 -> 3 -> 2 -> 1 -> None

Java: Iterative solution

public ListNode reverseList(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}

Java: Recursive solution

public ListNode reverseList(ListNode head) {
return reverseListInt(head, null);
} private ListNode reverseListInt(ListNode head, ListNode newHead) {
if (head == null)
return newHead;
ListNode next = head.next;
head.next = newHead;
return reverseListInt(next, head);
}  

Python: Iteration

def reverseList(self, head):
prev = None
while head:
curr = head
head = head.next
curr.next = prev
prev = curr
return prev

Python: Iteration

def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur, prev = head, None
while cur:
cur.next, prev, cur = prev, cur, cur.next
return prev

Python: Iteration

# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next)) class Solution:
def reverseList(self, head):
dummy = ListNode(0)
while head:
next = head.next
head.next = dummy.next
dummy.next = head
head = next
return dummy.next

Python: Recrusion

class Solution(object):
def reverseList(self, head, prev=None):
if not head:
return prev curr, head.next = head.next, prev
return self.reverseList(curr, head)  

Python: Recursion

class Solution:
def reverseList(self, head):
return self.doReverse(head, None)
def doReverse(self, head, newHead):
if head is None:
return newHead
next = head.next
head.next = newHead
return self.doReverse(next, head)

Python: Recursion, wo

class Solution(object):
def reverseList(self, head):
dummy = ListNode(0)
cur = self.recur(head, dummy)
return cur.next def recur(self, head1, head2):
if not head1:
return head2 next_node = head1.next
head1.next = head2.next
head2.next = head1
return self.recur(next_node, head2)  

C++: Iteration

/**
* 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) {
auto dummy = ListNode{0}; while (head) {
auto tmp = head->next;
head->next = dummy.next;
dummy.next = head;
head = tmp;
} return dummy.next;
}
};

C++: Recursion

class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The new head of reversed linked list.
*/
ListNode *reverse(ListNode *head) {
if (!head || !head->next) return head;
ListNode *t = head;
head = reverse(t->next);
t->next->next = t;
t->next = NULL;
return head;
}
};

   

类似题目:

[LeetCode] Reverse Linked List II 反向链表II

All LeetCode Questions List 题目汇总

[LeetCode] 206. Reverse Linked List 反向链表的更多相关文章

  1. [LeetCode] 206. Reverse Linked List ☆(反转链表)

    Reverse Linked List 描述 反转一个单链表. 示例: 输入: 1->2->3->4->5->NULL    输出: 5->4->3-> ...

  2. LeetCode 206. Reverse Linked List倒置链表 C++

    Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4-> ...

  3. [leetcode]206. Reverse Linked List反转链表

    Reverse a singly linked list. Input: 1->2->3->4->5->NULL Output: 5->4->3->2- ...

  4. leetcode 206. Reverse Linked List(剑指offer16)、

    206. Reverse Linked List 之前在牛客上的写法: 错误代码: class Solution { public: ListNode* ReverseList(ListNode* p ...

  5. 迭代和递归 - leetcode 206. Reverse Linked List

    Reverse Linked List,一道有趣的题目.给你一个链表,输出反向链表.因为我用的是JavaScript提交,所以链表的每个节点都是一个对象.例如1->2->3,就要得到3-& ...

  6. LeetCode 206. Reverse Linked List (倒转链表)

    Reverse a singly linked list. 题目标签:Linked List 题目给了我们一个链表,要求我们倒转链表. 利用递归,新设一个newHead = null,每一轮 把下一个 ...

  7. C++版 - 剑指offer 面试题16:反转链表(Leetcode 206: Reverse Linked List) 题解

    面试题16:反转链表 提交网址: http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId= ...

  8. LeetCode 206 Reverse Linked List(反转链表)(Linked List)(四步将递归改写成迭代)(*)

    翻译 反转一个单链表. 原文 Reverse a singly linked list. 分析 我在草纸上以1,2,3,4为例.将这个链表的转换过程先用描绘了出来(当然了,自己画的肯定不如博客上面精致 ...

  9. [LeetCode]206. Reverse Linked List(链表反转)

    Reverse a singly linked list. click to show more hints. Subscribe to see which companies asked this ...

随机推荐

  1. Codeforces B. Mouse Hunt(强连通分解缩点)

    题目描述: Mouse Hunt time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...

  2. sql分割函数

    drop function [dbo].[f_split] create function [dbo].[f_split] ( ),--需要分割的字符串(例如:1,2,3,4,5 我|和|你) )-- ...

  3. NodeJS 多版本管理(NVM)

    前言 现在前端各种框架更新较快,对 Node 的依赖也不一样,Node 的过版本管理也很有必要. NVM(Node Version Manager),是一个 Node 的版本管理工具. 官方的 NVM ...

  4. 《BUG创造队》第八次团队作业:Alpha冲刺

    项目 内容 这个作业属于哪个课程 2016级软件工程 这个作业的要求在哪里 实验十二 团队作业8:软件测试与ALPHA冲刺 团队名称 BUG创造队 作业学习目标 (1)掌握软件测试基础技术.(2)学习 ...

  5. 8、Python简单数据类型(int、float、complex、bool、str)

    一.数据类型分类 1.按存值个数区分 单个值:数字,字符串 多个值(容器):列表,元组,字典,集合 2.按可变不可变区分 可变:列表[],字典{},集合{} 不可变:数字,字符串,元组().bool, ...

  6. 性能:Receiver层面

    创建多个接收器 多个端口启动多个receiver在其他Executor,接收多个端口数据,在吞吐量上提高其性能.代码上: import org.apache.spark.storage.Storage ...

  7. [Javascript] Window.matchMedia()

    window.matchMedia() allow to listen to browser window size changes and trigger the callback for diff ...

  8. LeetCode 1060. Missing Element in Sorted Array

    原题链接在这里:https://leetcode.com/problems/missing-element-in-sorted-array/ 题目: Given a sorted array A of ...

  9. 使用docker来创建一个etcd集群

    docker run -d --name etcd1 --network etcdnet --ip 172.25.0.101 -p 23791:2379 -e ETCDCTL_API=3 -v /ro ...

  10. SpringCloud组件Eureka

    什么是微服务架构 架构设计概念,各服务间隔离(分布式也是隔离),自治(分布式依赖整体组合)其它特性(单一职责,边界,异步通信,独立部署)是分布式概念的跟严格执行SOA到微服务架构的演进过程作用:各服务 ...