Leetcode 24. 两两交换链表中的节点
题目链接:力扣
文章链接:代码随想录
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class ListNode(object):
def __init__(self, val = 0, next=None):
self.val = val
self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head ==None:
return
elif head.next == None:
return head
dummy_head = ListNode(next = head)
fIndex = dummy_head.next
bIndex = head.next
tmpf = dummy_head
tmpb = head.next.next
while tmpb:
tmpf.next = bIndex
bIndex.next = fIndex
fIndex.next = tmpb
# 更新tmpf、tmpb、fIndex、bIndex
tmpf = fIndex
fIndex = tmpb
bIndex = tmpb.next
if tmpb.next:
tmpb = tmpb.next.next
else:
return dummy_head.next
tmpf.next = bIndex
bIndex.next = fIndex
fIndex.next = tmpb
return dummy_head.next
Leetcode 19.删除链表的倒数第N个节点
题目链接:力扣
文章链接:代码随想录
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
# 虚拟头结点
dummy_head = ListNode(next=head)
#双指针
fastIndex = dummy_head
slowIndex = dummy_head
# fast移动n+1步
for _ in range(n+1):
if fastIndex == None:
return -1
fastIndex = fastIndex.next
while fastIndex:
slowIndex = slowIndex.next
fastIndex = fastIndex.next
# 删除结点
slowIndex.next = slowIndex.next.next
return dummy_head.next
Leetcode 面试题 02.07. 链表相交
题目链接:力扣
文章链接:代码随想录
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def getLen(head):
Len = 0
index = head
while index:
index = index.next
Len += 1
return Len
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
aLen = getLen(headA)
bLen = getLen(headB)
aIndex = headA
bIndex = headB
if aLen >= bLen:
motion = aLen -bLen
if motion == 0:
aIndex = headA
else:
for _ in range(motion):
aIndex = aIndex.next
else:
motion = bLen -aLen
for _ in range(motion):
bIndex = bIndex.next
while aIndex:
if aIndex == bIndex:
return aIndex
print(aIndex.val)
aIndex = aIndex.next
bIndex = bIndex.next
return aIndex
Leetcode 环形链表II
题目链接:力扣
文章链接:代码随想录
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# If there is a cycle, the slow and fast pointers will eventually meet
if slow == fast:
# Move one of the pointers back to the start of the list
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
# If there is no cycle, return None
return None
(补!!!)