File tree 3 files changed +55
-6
lines changed
solution/0200-0299/0206.Reverse Linked List
3 files changed +55
-6
lines changed Original file line number Diff line number Diff line change @@ -47,6 +47,8 @@ class Solution:
47
47
48
48
### ** Java**
49
49
50
+ 迭代版本:
51
+
50
52
``` java
51
53
/**
52
54
* Definition for singly-linked list.
@@ -58,8 +60,7 @@ class Solution:
58
60
*/
59
61
class Solution {
60
62
public ListNode reverseList (ListNode head ) {
61
- ListNode pre = null ;
62
- ListNode p = head;
63
+ ListNode pre = null , p = head;
63
64
while (p != null ) {
64
65
ListNode q = p. next;
65
66
p. next = pre;
@@ -71,6 +72,30 @@ class Solution {
71
72
}
72
73
```
73
74
75
+ 递归版本:
76
+
77
+ ``` java
78
+ /**
79
+ * Definition for singly-linked list.
80
+ * public class ListNode {
81
+ * int val;
82
+ * ListNode next;
83
+ * ListNode(int x) { val = x; }
84
+ * }
85
+ */
86
+ class Solution {
87
+ public ListNode reverseList (ListNode head ) {
88
+ if (head == null || head. next == null ) {
89
+ return head;
90
+ }
91
+ ListNode res = reverseList(head. next);
92
+ head. next. next = head;
93
+ head. next = null ;
94
+ return res;
95
+ }
96
+ }
97
+ ```
98
+
74
99
### ** JavaScript**
75
100
76
101
``` js
Original file line number Diff line number Diff line change @@ -46,6 +46,8 @@ class Solution:
46
46
47
47
### ** Java**
48
48
49
+ Iterative version:
50
+
49
51
``` java
50
52
/**
51
53
* Definition for singly-linked list.
@@ -57,8 +59,7 @@ class Solution:
57
59
*/
58
60
class Solution {
59
61
public ListNode reverseList (ListNode head ) {
60
- ListNode pre = null ;
61
- ListNode p = head;
62
+ ListNode pre = null , p = head;
62
63
while (p != null ) {
63
64
ListNode q = p. next;
64
65
p. next = pre;
@@ -70,6 +71,30 @@ class Solution {
70
71
}
71
72
```
72
73
74
+ Recursive version:
75
+
76
+ ``` java
77
+ /**
78
+ * Definition for singly-linked list.
79
+ * public class ListNode {
80
+ * int val;
81
+ * ListNode next;
82
+ * ListNode(int x) { val = x; }
83
+ * }
84
+ */
85
+ class Solution {
86
+ public ListNode reverseList (ListNode head ) {
87
+ if (head == null || head. next == null ) {
88
+ return head;
89
+ }
90
+ ListNode res = reverseList(head. next);
91
+ head. next. next = head;
92
+ head. next = null ;
93
+ return res;
94
+ }
95
+ }
96
+ ```
97
+
73
98
### ** JavaScript**
74
99
75
100
``` js
Original file line number Diff line number Diff line change 8
8
*/
9
9
class Solution {
10
10
public ListNode reverseList (ListNode head ) {
11
- ListNode pre = null ;
12
- ListNode p = head ;
11
+ ListNode pre = null , p = head ;
13
12
while (p != null ) {
14
13
ListNode q = p .next ;
15
14
p .next = pre ;
You can’t perform that action at this time.
0 commit comments