File tree 2 files changed +63
-1
lines changed
src/com/andavid/leetcode/_206
2 files changed +63
-1
lines changed Original file line number Diff line number Diff line change @@ -8,7 +8,7 @@ Reverse a singly linked list.
8
8
9
9
A linked list can be reversed either iteratively or recursively. Could you implement both?
10
10
11
- ## 思路
11
+ ## 思路一
12
12
13
13
使用两个变量分别记录当前节点的前一个节点和后一个节点,当遍历链表的时候,将当前节点的 next 节点修改为前一个节点。
14
14
@@ -38,5 +38,26 @@ class Solution {
38
38
}
39
39
```
40
40
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
+
41
61
[ title ] : https://leetcode.com/problems/reverse-linked-list
42
62
[ 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 number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments