2021.9.7
92、反转链表(中等)
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
prev = None
curr = head
next = head
for i in range(left-1):
prev = curr
curr = curr.next
prev2 = prev
curr2 = curr
for i in range(right - left +1):
next = curr.next
curr.next = prev
prev = curr
curr = next
if prev2 != None:
prev2.next = prev
else:
head = prev
curr2.next = curr
return head
61 旋转链表(中等)
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if head == None or head.next == None or k == 0:
return head
len = 1
curr = head
while curr.next:
len += 1
curr = curr.next
k %=len
if k== 0:
return head
temp = head
for i in range(len - k -1):
temp = temp.next
new_head = temp.next
curr.next = head
temp.next = None
return new_head
143、重排链表
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return head
temp = []
while head:
temp.append(head)
head = head.next
for i in range(len(temp)//2):
temp[i].next = temp[~i]
temp[~i].next = temp[i+1]
temp[len(temp)//2].next = None
return temp[0]
纯属记录,如有雷同,算我抄袭
|