Skip to content

Commit 51ab802

Browse files
committed
update 206
1 parent 147dc07 commit 51ab802

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

note/206/README.md

+22-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ Reverse a singly linked list.
88

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

11-
## 思路
11+
## 思路一
1212

1313
使用两个变量分别记录当前节点的前一个节点和后一个节点,当遍历链表的时候,将当前节点的 next 节点修改为前一个节点。
1414

@@ -38,5 +38,26 @@ class Solution {
3838
}
3939
```
4040

41+
## 思路二
42+
43+
使用递归。
44+
45+
## [完整代码][src2]
46+
47+
```java
48+
class Solution {
49+
public ListNode reverseList(ListNode head) {
50+
if (head == null || head.next == null) {
51+
return head;
52+
}
53+
ListNode p = reverseList(head.next);
54+
head.next.next = head;
55+
head.next = null;
56+
return p;
57+
}
58+
}
59+
```
60+
4161
[title]: https://leetcode.com/problems/reverse-linked-list
4262
[src]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_206/Solution.java
63+
[src2]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_206/Solution2.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution2 {
2+
3+
public static ListNode reverseList(ListNode head) {
4+
if (head == null || head.next == null) {
5+
return head;
6+
}
7+
ListNode p = reverseList(head.next);
8+
head.next.next = head;
9+
head.next = null;
10+
return p;
11+
}
12+
13+
public static class ListNode {
14+
int val;
15+
ListNode next;
16+
ListNode(int x) {
17+
val = x;
18+
}
19+
}
20+
21+
public static void main(String[] args) {
22+
ListNode node1 = new ListNode(1);
23+
ListNode node2 = new ListNode(2);
24+
ListNode node3 = new ListNode(3);
25+
ListNode node4 = new ListNode(4);
26+
ListNode node5 = new ListNode(5);
27+
node1.next = node2;
28+
node2.next = node3;
29+
node3.next = node4;
30+
node4.next = node5;
31+
node5.next = null;
32+
33+
ListNode node = reverseList(node1);
34+
while(node.next != null) {
35+
System.out.print(node.val + ",");
36+
node = node.next;
37+
}
38+
System.out.print(node.val);
39+
}
40+
41+
}

0 commit comments

Comments
 (0)