24. 两两交换链表中的节点:
代码思路
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None:
return None
if head.next == None:
return head
n = 0
pre_node = ListNode(val=-1, next=head)
pre = pre_node
cur = head
while cur != None:
if n % 2 == 0:
if cur.next != None:
pre.next = cur.next
pre = cur
cur = cur.next
else:
next = cur.next
cur.next = pre
pre.next = next
cur = next
n += 1
return pre_node.next
19. 删除链表的倒数第N个节点
代码思路
该题是先构建节点的类,再在链表的类中调用节点类。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
count = 1
pre_node = ListNode(-1, head)
temp_head = pre_node
temp_tail = head
while count < n and temp_tail != None:
temp_tail = temp_tail.next
count += 1
while temp_tail.next != None:
temp_head = temp_head.next
temp_tail = temp_tail.next
temp_head.next = temp_head.next.next
return pre_node.next
def deleteAtIndex(self, index: int) -> None:
pre = None
cur = self.head
if cur:
if index == 0:
self.head = self.head.next
return None
n = 0
while n < index:
if cur.next == None:
return None
else:
pre = cur
cur = cur.next
n += 1
pre.next = cur.next
面试题 02.07. 链表相交
代码思路
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
curA, curB = headA, headB
len_A = 1
while curA != None:
curA = curA.next
len_A += 1
len_B = 1
while curB != None:
curB = curB.next
len_B += 1
if len_A > len_B:
longer, shorter = headA, headB
diff = len_A - len_B
else:
shorter, longer = headA, headB
diff = len_B - len_A
longer_begin = longer
count = 0
while count < diff:
longer_begin = longer_begin.next
count += 1
count = 0
while longer_begin != None:
if longer_begin != shorter:
longer_begin = longer_begin.next
shorter = shorter.next
else:
return longer_begin
count += 1
return None
142.环形链表II
代码思路
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast = head
slow = None
while fast != slow:
if slow == None:
slow = head
if fast == None or fast.next == None:
return None
fast = fast.next.next
slow = slow.next
ptr = head
while slow != ptr:
slow = slow.next
ptr = ptr.next
return ptr