# 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)

900 篇文章 155 订阅
1033 篇文章 56 订阅

id： fuxuemingzhu

### 目录

[LeetCode]

Total Accepted: 105474 Total Submissions: 267077 Difficulty: Easy

## 题目描述

Example:

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


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

## 解题方法

### 迭代

old->3->4->5->NULL
new->2->1

old->4->5->NULL
new->3->2->1


Java代码如下：

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


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""
dummy = ListNode(-1)
return dummy.next


/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* dummy = new ListNode(0);
ListNode* old = dummy->next;
}
return dummy->next;
}
};


### 递归

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) {
return p;
}


python的递归写法。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""



C++代码如下：

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
}
}
};


## 日期

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

• 1
点赞
• 0
收藏
• 打赏
• 0
评论
02-17 3613
11-02 189
10-26 50
05-16 249
05-07 91
12-11 1万+
05-17 122
06-15 495
08-28 131
07-30 2003

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。