Update 0206.翻转链表.md

This commit is contained in:
jianghongcheng
2023-05-03 17:18:48 -05:00
committed by GitHub
parent 70d8379ff7
commit 55ea26c5bd

View File

@ -193,9 +193,9 @@ class Solution {
}
```
Python迭代法:
Python
```python
#双指针
版本一双指针
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
@ -205,7 +205,7 @@ class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur = head
pre = None
while(cur!=None):
while cur:
temp = cur.next # 保存一下 cur的下一个节点因为接下来要改变cur->next
cur.next = pre #反转
#更新pre、cur指针
@ -217,6 +217,7 @@ class Solution:
Python递归法
```python
版本二递归法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
@ -224,36 +225,17 @@ Python递归法
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def reverse(pre,cur):
if not cur:
return pre
tmp = cur.next
cur.next = pre
return reverse(cur,tmp)
return reverse(None,head)
return self.reverse(head, None)
def reverse(self, cur: ListNode, pre: ListNode) -> ListNode:
if cur == None:
return pre
temp = cur.next
cur.next = pre
return self.reverse(temp, cur)
```
Python递归法从后向前
```python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next: return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
```
Go