@@ -25,7 +25,7 @@ A linked list can be reversed either iteratively or recursively. Could you imple
2525
2626## 代码
2727
28- 语言支持:JS, C++
28+ 语言支持:JS, C++, Python
2929
3030JavaScript Code:
3131
@@ -44,19 +44,19 @@ JavaScript Code:
4444 * Testcase Example: '[1,2,3,4,5]'
4545 *
4646 * Reverse a singly linked list.
47- *
47+ *
4848 * Example:
49- *
50- *
49+ *
50+ *
5151 * Input: 1->2->3->4->5->NULL
5252 * Output: 5->4->3->2->1->NULL
53- *
54- *
53+ *
54+ *
5555 * Follow up:
56- *
56+ *
5757 * A linked list can be reversed either iteratively or recursively. Could you
5858 * implement both?
59- *
59+ *
6060 */
6161/**
6262 * Definition for singly-linked list.
@@ -86,7 +86,9 @@ var reverseList = function(head) {
8686};
8787
8888```
89+
8990C++ Code:
91+
9092``` C++
9193/* *
9294 * Definition for singly-linked list.
@@ -112,6 +114,26 @@ public:
112114 }
113115};
114116```
117+
118+ Python Code:
119+
120+ ```python
121+ # Definition for singly-linked list.
122+ # class ListNode:
123+ # def __init__(self, x):
124+ # self.val = x
125+ # self.next = None
126+
127+ class Solution:
128+ def reverseList(self, head: ListNode) -> ListNode:
129+ if not head: return None
130+ prev = None
131+ cur = head
132+ while cur:
133+ cur.next, prev, cur = prev, cur, cur.next
134+ return prev
135+ ```
136+
115137## 拓展
116138
117139通过单链表的定义可以得知,单链表也是递归结构,因此,也可以使用递归的方式来进行reverse操作。
@@ -133,7 +155,7 @@ public:
133155 ListNode* tail = nullptr;
134156 return reverseRecursive(head, tail);
135157 }
136-
158+
137159 ListNode* reverseRecursive(ListNode *head, ListNode *&tail) {
138160 if (head == nullptr) {
139161 tail = nullptr;
@@ -160,7 +182,7 @@ public:
160182 if (head == nullptr) return head;
161183 return reverseRecursive(nullptr, head, head->next);
162184 }
163-
185+
164186 ListNode* reverseRecursive(ListNode *prev, ListNode *head, ListNode *next)
165187 {
166188 if (next == nullptr) return head;
0 commit comments