添加py,提供另一种解法

pull/33/head
jaredliw 2021-07-13 12:27:36 +08:00
parent b48730dd5b
commit ea1335f661
1 changed files with 76 additions and 18 deletions

View File

@ -25,11 +25,9 @@
temp low
low = temp
low = temp
@ -41,15 +39,10 @@ Java Code:
```java
class Solution {
public ListNode reverseList(ListNode head) {
//特殊情况
//特殊情况
if (head == null || head.next == null) {
return head;
}
//反转
return reverse(head);
}
public ListNode reverse (ListNode head) {
ListNode low = null;
ListNode pro = head;
while (pro != null) {
@ -64,42 +57,41 @@ class Solution {
}
return low;
}
}
```
JS Code:
```javascript
var reverseList = function(head) {
//特殊情况
if(!head || !head.next) {
return head;
}
let low = null;
let pro = head;
while (pro) {
//代表橙色指针
let temp = pro;
//移动绿色指针
pro = pro.next;
//反转节点
temp.next = low;
//移动黄色指针
low = temp;
}
return low;
};
```
C++
C++ Code:
```cpp
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//特殊情况
//特殊情况
if (head == nullptr || head->next == nullptr) {
return head;
}
//反转
return reverse(head);
}
ListNode * reverse (ListNode * head) {
ListNode * low = nullptr;
ListNode * pro = head;
while (pro != nullptr) {
@ -117,6 +109,28 @@ public:
};
```
Python Code:
```py
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
//特殊情况
if head is None or head.next is None:
return head
low = None
pro = head
while pro is not None:
#
temp = pro
# 绿
pro = pro.next
#
temp.next = low
#
low = temp
return low
```
@ -148,11 +162,17 @@ class Solution {
JS Code:
```javascript
var reverseList = function(head) {
//结束条件
if (!head || !head.next) {
return head;
}
//保存最后一个节点
let pro = reverseList(head.next);
//将节点进行反转。我们可以这样理解 4.next.next = 4;
//4.next = 5
//则 5.next = 4 则实现了反转
head.next.next = head;
//防止循环
head.next = null;
return pro;
};
@ -181,3 +201,41 @@ public:
};
```
Python Code:
```py
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
#
if head is None or head.next is None:
return head
#
pro = self.reverseList(head.next)
# 4->next->next = 4;
# 4->next = 5
# 5->next = 4
head.next.next = head
#
head.next = None
return pro
```
<br/>
> [@jaredliw](https://github.com/jaredliw)注:
>
>
>
> ```py
> class Solution:
> def reverseList(self, head: ListNode, prev_nd: ListNode = None) -> ListNode:
> #
> if head is None:
> return prev_nd
> #
> next_nd = head.next
> head.next = prev_nd
> #
> return self.reverseList(next_nd, head)
> ```