题目链接:24. 两两交换链表中的节点 - 力扣(LeetCode)
思路:两两交换节点,加入虚拟头节点可以让每一轮循环的操作不用加入额外的判断。交换节点需要进行三部,这里将需要交换的两个节点记为a->b,记a之前的节点为current,b之后的节点为after 即:current->a->b。
step1:current的next指向b
step2:b的next指向a
step3:a的next指向after
在改变current的next时会丢失指向a的链,会进行断链,所以要进行保存,记录为temp_1
在改变b的next时会丢失指向after的链,会进行断链,所以要进行保存,记录为temp_2
完整代码如下:
# Definition for singly-linked list.
# 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
"""
dummy_head = ListNode(next = head)
current = dummy_head
while current.next != None and current.next.next != None: #current.next存在节点
temp = current.next #
temp_2 = current.next.next.next #
current.next = temp.next
current.next.next = temp
temp.next = temp_2
current = current.next.next
return dummy_head.next
题目链接:19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
思路:快慢指针,先让快指针移动n次,然后快慢指针一起移动,当fast.next == None 时,slow就到了删除节点的前一个节点,然后就可以进行删除
# Definition for singly-linked list.
# 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)
fast = dummy_head
slow = dummy_head
for i in range(n):
fast = fast.next
while fast.next != None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy_head.next
题目链接:面试题 02.07. 链表相交 - 力扣(LeetCode)
思路:先选出长链表,长链表和短链表长度的差值定为n,先让fast指针在长链表上移动n步,然后fast和slow指针同时移动,如果碰到交点就返回,如果到底没有就返回None。
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
p = headA
q = headB
ALength = 0
BLength = 0
while p:
ALength += 1
p = p.next
while q:
BLength += 1
q = q.next
dummy_head_A = ListNode(next = headA)
dummy_head_B = ListNode(next = headB)
if ALength > BLength:
fast = dummy_head_A
slow = dummy_head_B
else:
fast = dummy_head_B
slow = dummy_head_A
n = abs(ALength - BLength)
for i in range(n):
fast = fast.next
print("this")
while fast.next:
if fast == slow:
return fast
fast = fast.next
slow = slow.next
return fast if fast == slow else None
题目链接:142. 环形链表 II - 力扣(LeetCode)
# 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
"""
if head == None or head.next == None:
return None
dummy_head = ListNode(next = head)
fast = dummy_head
slow = dummy_head
fast = fast.next.next
slow = slow.next
while fast != slow:
if fast == None:
return None
fast = fast.next
if fast == None:
return None
else:
fast = fast.next
slow = slow.next
P = dummy_head
while P != slow:
P = P.next
slow = slow.next
return slow