作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


[LeetCode]

题目地址:https://leetcode.com/problems/reverse-linked-list/

Total Accepted: 105474 Total Submissions: 267077 Difficulty: Easy

题目描述

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

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

题目大意

翻转单链表。

解题方法

迭代

迭代解法,每次找出老链表的下一个结点,插入到新链表的头结点,这样就是一个倒着的链。

举例说明:

old->3->4->5->NULL
new->2->1
然后把3插入到new的后边,会变成:
old->4->5->NULL
new->3->2->1

Java代码如下:

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

二刷,python。

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
newHead = None
while head != None:
temp = head.next
head.next = newHead
newHead = head
head = temp
return newHead

三刷,python。下面的解法打败了100%.

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(-1)
while head:
nodenext = head.next
head.next = dummy.next
dummy.next = head
head = nodenext
return dummy.next

四刷,C++代码如下:

/**
* 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* dummy = new ListNode(0);
while (head) {
ListNode* old = dummy->next;
ListNode* nxt = head->next;
dummy->next = head;
head->next = old;
head = nxt;
}
return dummy->next;
}
};

递归

递归,先把除了head以外的后面部分翻转,然后把head放到已经翻转了的链表的结尾即可。需要注意的是找到已经翻转了的链表结尾并不是遍历找的,而是通过head.next.next = head;这一步,原因是head.next是老链表的除了head以外的头,也就是说新链表的结尾。

1 → … → nk-1 → nk → nk+1 → … → nm → Ø

Assume from node nk+1 to nm had been reversed and you are at node nk.

n1 → … → nk-1 → nk → nk+1 ← … ← nm

We want nk+1’s next node to point to nk.

So,

nk.next.next = nk;

Be very careful that n1’s next must point to Ø. If you forget about this, your linked list has a cycle in it. This bug could be caught if you test your code with a linked list of size 2.

Java代码如下:

public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}

另外一种递归解法是新增加一个函数,让其有两个参数,第一个参数表示剩余链表的头,第二个参数表示新链表的头。每次把剩余链表的头插入到新链表的头部,返回该新的头部即可,这样的翻转就更直观了。

python的递归写法。

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
return self.reverse(head, None) def reverse(self, head, newHead):
if not head:
return newHead
headnext = head.next
head.next = newHead
return self.reverse(headnext, head)

C++代码如下:

/**
* 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) {
return reverse(head, nullptr);
}
ListNode* reverse(ListNode* oldHead, ListNode* newHead) {
if (!oldHead) return newHead;
ListNode* nxt = oldHead->next;
oldHead->next = newHead;
return reverse(nxt, oldHead);
}
};

日期

2016/5/1 12:50:33
2018年3月11日
2018 年 11 月 11 日 —— 剁手节快乐
2019 年 9 月 17 日 —— 听了hulu宣讲会,觉得hulu的压力不大

【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)的更多相关文章

  1. LeetCode 206 Reverse Linked List 解题报告

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

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

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

  3. [LeetCode] 206. Reverse Linked List 反向链表

    Reverse a singly linked list. Hint: A linked list can be reversed either iteratively or recursively. ...

  4. Java for LeetCode 206 Reverse Linked List

    Reverse a singly linked list. 解题思路: 用Stack实现,JAVA实现如下: public ListNode reverseList(ListNode head) { ...

  5. Java [Leetcode 206]Reverse Linked List

    题目描述: Reverse a singly linked list. 解题思路: 使用递归或者迭代的方法. 代码如下: 方法一:递归 /** * Definition for singly-link ...

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

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

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

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

  8. 【LeetCode】1019. Next Greater Node In Linked List 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 单调递减栈 日期 题目地址:https://leetc ...

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

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

随机推荐

  1. 【GS文献】基因组选择在植物分子育种应用的最新综述(2020)

    目录 1. 简介 2. BLUP类模型 3. Bayesian类模型 4. 机器学习 5. GWAS辅助的GS 6. 杂交育种 7. 多性状 8. 长期选择 9. 预测准确性评估 10. GS到植物育 ...

  2. git添加新账号

    1,在linux上添加账号 useradd test passwd test usermod -G gitgroup  test  将test账号的组改为和git一样的组gitgroup  git所在 ...

  3. (转载) IBM DB2数据库odbc配置步骤详解

    [IT168 技术] 首先安装IBM DB2 odbc driver 1):可以单独下载DB2 Run-Time Client,大约(86.6m),安装后则odbc驱动程序安装成功.下载地址:ftp: ...

  4. Shell 统计文件的行数

    目录 统计文件的行数 题目 题解-awk 题解-wc 题解sed 统计文件的行数 题目 写一个 bash脚本以输出一个文本文件 nowcoder.txt中的行数 示例: 假设 nowcoder.txt ...

  5. 日常Java 2021/10/20

    Java提供了一套实现Collection接口的标准集合类 bstractCollection 实现了大部分的集合接口. AbstractList 继承于AbstractCollection并且实现了 ...

  6. A Child's History of England.32

    And so, in darkness and in prison, many years, he thought of all his past life, of the time he had w ...

  7. python web工程师跳巢攻略

    python web工程师跳巢攻略 流程 一面问基础 二面问项目 三面问设计(经验) web请求的流程 浏览器 负载均衡 web框架 业务逻辑 数据库缓存 后端技术栈 python语言基础 语言特点 ...

  8. IPv6 私有地址

    在互联网的地址架构中,专用网络是指遵守RFC 1918(IPV4)和RFC 4193(IPV6)规范,使用专用IP地址空间的网络.私有IP无法直接连接互联网,需要使用网络地址转换(Network Ad ...

  9. linux 挂载本地iso

    mount -t iso9660 -o loop /mnt/temp/rhel-server-6.5-i386-dvd.iso /mnt/cdrom -t :设备类型 iso9660是指CD-ROM光 ...

  10. Classs类

    Classs类如何获得 获得Class对象 方式一: 通过Object类中的getClass()方法 方式二: 通过 类名.class 获取到字节码文件对象( 方式三: 通过Class类中的方法(将类 ...