【代码随想录】day 4 24.两两交换链表中的节点 19.删除链表的倒数第n个节点
24.两两交换链表中的节点
还是采用虚拟头节点的方式
三个步骤
cur要指向调换位置的前一个,时刻要清楚cur到底是指向哪里的
# 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)
cur = dummy_head
while cur.next and cur.next.next:
temp1 = cur.next
temp2 = cur.next.next.next
cur.next = cur.next.next
cur.next.next = temp1
temp1.next = temp2
cur = cur.next.next
return dummy_head.next
19.删除链表的倒数第n个节点
运用快慢双指针
删除节点也要指向删除的前一个节点
注意边界条件
# 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 = slow = dummy_head
for _ in range (n+1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy_head.next
142.环形链表
使用快慢两个指针,同一个起点,慢指针走一步,快指针走两步,如果相遇,就说明肯定有环
判断环节点的位置,根据等式可以得到,在环中相遇之后,一个指针从起点,一个指针从相遇点,以相同的速度前进,就会在环入口处相遇。
# 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
"""
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if slow == fast:
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
return None