【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)
作者: 负雪明烛
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)的更多相关文章
- LeetCode 206 Reverse Linked List 解题报告
题目要求 Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5-> ...
- leetcode 206. Reverse Linked List(剑指offer16)、
206. Reverse Linked List 之前在牛客上的写法: 错误代码: class Solution { public: ListNode* ReverseList(ListNode* p ...
- [LeetCode] 206. Reverse Linked List 反向链表
Reverse a singly linked list. Hint: A linked list can be reversed either iteratively or recursively. ...
- Java for LeetCode 206 Reverse Linked List
Reverse a singly linked list. 解题思路: 用Stack实现,JAVA实现如下: public ListNode reverseList(ListNode head) { ...
- Java [Leetcode 206]Reverse Linked List
题目描述: Reverse a singly linked list. 解题思路: 使用递归或者迭代的方法. 代码如下: 方法一:递归 /** * Definition for singly-link ...
- 迭代和递归 - leetcode 206. Reverse Linked List
Reverse Linked List,一道有趣的题目.给你一个链表,输出反向链表.因为我用的是JavaScript提交,所以链表的每个节点都是一个对象.例如1->2->3,就要得到3-& ...
- [LeetCode] 206. Reverse Linked List ☆(反转链表)
Reverse Linked List 描述 反转一个单链表. 示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3-> ...
- 【LeetCode】1019. Next Greater Node In Linked List 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 单调递减栈 日期 题目地址:https://leetc ...
- C++版 - 剑指offer 面试题16:反转链表(Leetcode 206: Reverse Linked List) 题解
面试题16:反转链表 提交网址: http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId= ...
随机推荐
- git冲突
常规操作: # quan @ quandeMacBook-Pro in ~/Desktop/10-01/app_addressing----quan on git:1.0.1.Release o [1 ...
- Scrapy框架延迟请求之Splash的使用
Splash是什么,用来做什么 Splash, 就是一个Javascript渲染服务.它是一个实现了HTTP API的轻量级浏览器,Splash是用Python实现的,同时使用Twisted和QT.T ...
- No.1 R语言在生物信息中的应用——序列读取及格式化输出
目的:读入序列文件(fasta格式),返回一个数据框,内容包括--存储ID.注释行(anno).长度(len).序列内容(content) 一.问题思考: 1. 如何识别注释行和序列内容行 2. 如何 ...
- kubernetes部署 docker 容器
docker 容器相对比较简单,不涉及认证授权,只需要本地启动起来即可,唯一需要注意就是添加flannel网络. # yum remove docker-latest-logrotate docker ...
- 8.7 进程间的通讯:管道、消息队列、共享内存、信号量、信号、Socket
进程间的通讯 进程间为什么需要通讯? 共享数据.数据传输.消息通知.进程控制 进程间的通讯有哪些类型? 首先,联系前面讲过的知识,进程之间的用户地址空间是相互独立的,不能进行互相访问,但是,内核空间却 ...
- day31 协程
day31 协程 一.死锁与递归锁 所谓死锁:是指两个或者两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去.此时称系统处于死锁状态或系统产 ...
- 转 Android Monkey压力测试使用
转自:https://www.jianshu.com/p/c8844327f5e9 一.Monkey简介: Monkey是Android中的一个命令行工具,可以运行在模拟器里或者现实设备中,向系统发送 ...
- AI常用环境安装
torch环境 conda create --name py37 python=3.7 conda activate py37 pip install jieba==0.42.1pip install ...
- 深入 char
深入 char * ,char ** ,char a[ ] ,char *a[] 内核分类: c语言 2013-02-23 15:34 15176人阅读 评论(8) 收藏 举报Charcharchar ...
- entfrm-app赋能entfrm零代码开发平台 开启多平台分发
entfrm-app是基于uni-app 框架.使用 Vue.js 语法开发的移动端 App开源产品.它可以编译为 H5.IOS App.Android App.微信小程序.QQ小程序.钉钉小程序.支 ...