mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 12:15:58 +08:00
Update 0206.翻转链表.md
This commit is contained in:
@ -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:
|
||||
|
||||
|
Reference in New Issue
Block a user