mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-12 21:50:49 +08:00
Update 0206.翻转链表.md
This commit is contained in:
@ -193,9 +193,9 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Python迭代法:
|
Python
|
||||||
```python
|
```python
|
||||||
#双指针
|
(版本一)双指针法
|
||||||
# Definition for singly-linked list.
|
# Definition for singly-linked list.
|
||||||
# class ListNode:
|
# class ListNode:
|
||||||
# def __init__(self, val=0, next=None):
|
# def __init__(self, val=0, next=None):
|
||||||
@ -205,7 +205,7 @@ class Solution:
|
|||||||
def reverseList(self, head: ListNode) -> ListNode:
|
def reverseList(self, head: ListNode) -> ListNode:
|
||||||
cur = head
|
cur = head
|
||||||
pre = None
|
pre = None
|
||||||
while(cur!=None):
|
while cur:
|
||||||
temp = cur.next # 保存一下 cur的下一个节点,因为接下来要改变cur->next
|
temp = cur.next # 保存一下 cur的下一个节点,因为接下来要改变cur->next
|
||||||
cur.next = pre #反转
|
cur.next = pre #反转
|
||||||
#更新pre、cur指针
|
#更新pre、cur指针
|
||||||
@ -217,6 +217,7 @@ class Solution:
|
|||||||
Python递归法:
|
Python递归法:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
(版本二)递归法
|
||||||
# Definition for singly-linked list.
|
# Definition for singly-linked list.
|
||||||
# class ListNode:
|
# class ListNode:
|
||||||
# def __init__(self, val=0, next=None):
|
# def __init__(self, val=0, next=None):
|
||||||
@ -224,36 +225,17 @@ Python递归法:
|
|||||||
# self.next = next
|
# self.next = next
|
||||||
class Solution:
|
class Solution:
|
||||||
def reverseList(self, head: ListNode) -> ListNode:
|
def reverseList(self, head: ListNode) -> ListNode:
|
||||||
|
return self.reverse(head, None)
|
||||||
def reverse(pre,cur):
|
def reverse(self, cur: ListNode, pre: ListNode) -> ListNode:
|
||||||
if not cur:
|
if cur == None:
|
||||||
return pre
|
return pre
|
||||||
|
temp = cur.next
|
||||||
tmp = cur.next
|
|
||||||
cur.next = pre
|
cur.next = pre
|
||||||
|
return self.reverse(temp, cur)
|
||||||
return reverse(cur,tmp)
|
|
||||||
|
|
||||||
return reverse(None,head)
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
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:
|
Go:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user