24. 两两交换链表中的节点
题目链接:Swap Nodes in Pairs - LeetCode
题目链接/文章讲解/视频讲解: 代码随想录
解题思路:
看是否有head和head.next,如果没有直接返回
有的话可以进入下一步
先设置fake_head作为起始链接pre,进入循环若有pre.next和pre.next.next说明可以进行交换,
因为交换会断链,先temp一下后面的链表,在链接前面的,pre 1 2 中pre接2,2接1, 1接temp
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
if not head.next:
return head
fk_head=ListNode(None)
fk_head.next= head
pre=fk_head
while pre.next and pre.next.next:
first=pre.next
second=pre.next.next
temp=second.next
first.next=temp
second.next=first
pre.next=second
pre=pre.next.next
return fk_head.next
化简
class Solution(object):
def swapPairs(self, head: ListNode):
res = ListNode(next=head)
pre = res
# 必须有pre的下一个和下下个才能交换,否则说明已经交换结束了
while pre.next and pre.next.next:
cur = pre.next
post = pre.next.next
# pre,cur,post对应最左,中间的,最右边的节点
cur.next = post.next
post.next = cur
pre.next = post
pre = pre.next.next
return res.next
- 时间复杂度:O(n)
- 空间复杂度:O(1)
19.删除链表的倒数第N个节点
题目链接:Remove Nth Node From End of List - LeetCode
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
快慢指针
fake head yyds
设置快慢指针,让快指针先走n步,然后快慢指针同时走,走到尾时慢指针所指的就是倒数第n个,为了断链接我们应该找到前一位所以将改一下快指针让其先走n+1步。
重建slow指针的链接
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
fk_head = ListNode()
fk_head.next = head
slow = fk_head
fast = fk_head
for i in range(n+1):
fast = fast.next
while fast:
slow=slow.next
fast=fast.next
slow.next=slow.next.next
return fk_head.next
- 时间复杂度:O(n)
- 空间复杂度:O(1)
面试题 02.07. 链表相交
题目链接: Intersection of Two Linked Lists - LeetCode
题目链接/文章讲解:代码随想录
解题思路:
先遍历长度
长的设置为a,短的为b
将a,b的起始位置调平 同时开始遍历,如果当前node相等就返回, 如果不想等继续遍历
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
count_a=0
count_b=0
cur_a=headA
cur_b=headB
while cur_a:
cur_a=cur_a.next
count_a+=1
while cur_b:
cur_b=cur_b.next
count_b+=1
curA=headA
curB=headB
if count_a<count_b:
curA,curB=headB,headA
for i in range(abs(count_a-count_b)):
curA=curA.next
while curA:
if curA==curB:
return curA
else:
curA=curA.next
curB=curB.next
return None
- 时间复杂度:O(n + m)
- 空间复杂度:O(1)
142.环形链表II
题目链接:Linked List Cycle II - LeetCode
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
双指针
1. 先判断有没有圈
慢走一步 快走两步 总会相遇。 不相遇就不是。
2. 判断什么是起点
如果是圈的话 那就确认圈的起点
相遇的点到起点的位置等于 head到起点的距离 那么此时我们只需要在判断完是圈后重新设定两个指针以相同的速度出发 碰到就是起点。
1套2
# 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,fast=head,head
while fast and fast.next:
slow=slow.next
fast=fast.next.next
if slow==fast:
p=slow
q=head
while p.next:
if p == q:
return q
p=p.next
q=q.next
return None