# 24.两两交换链表中的节点
- 链接:帮你把链表细节学清楚! | LeetCode:24. 两两交换链表中的节点_哔哩哔哩_bilibili
- 第一想法:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy_head = ListNode(next=head)
cur = dummy_head
while cur.next and cur.next.next:
tmp = cur.next.next
cur.next.next = tmp.next
cur.next.next.next = cur.next
cur.next = tmp
cur = cur.next.next
return dummy_head.next
只用了tmp,然后一直报超出时间限制。
- 看完代码随想录的想法:
需要俩tmp来暂存cur.next 和 cur.next.next
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy_head = ListNode(next=head)
cur = dummy_head
while cur.next and cur.next.next:
p1 = cur.next
p2 = cur.next.next
p1.next = p2.next
p2.next = p1
cur.next = p2
cur = cur.next.next
return dummy_head.next
# 19. 删除链表的倒数第N个结点
- 链接:链表遍历学清楚! | LeetCode:19.删除链表倒数第N个节点_哔哩哔哩_bilibili
- 第一想法:
遍历整个链表,确认链表长度,设为length
减去n,得到指针要到的位置
然后进行删除
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummyhead = ListNode(next = head)
cur = dummyhead
pre = dummyhead
count = 0
while pre.next:
count += 1
pre = pre.next
index = count - n
while index:
cur = cur.next
index -= 1
cur.next = cur.next.next
return dummyhead.next
- 看完代码随想录的想法:
原来可以使用双指针。还有就是把fast先遍历到n+1的位置。这个想法很妙。
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummyhead = ListNode(next = head)
slow = dummyhead
fast = dummyhead
index = n+1
while index:
fast = fast.next
index -= 1
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummyhead.next
# 面试题 02.07.链表相交
- 链接:代码随想录
- 第一想法:
用两个while loop 遍历俩链表,看什么时候相交。超时。
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
curA = ListNode(next=headA)
while curA.next:
curB = ListNode(next=headB)
while curB.next:
if curA.next == curB.next:
return curA.next
curB = curB.next
curA = curA.next
- 看完代码随想录的想法:
重点: 如果是相交,后面的部分都应该一样。这个写法有点类似我做19的第一想法
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
curA = headA
curB = headB
lenA = 0
lenB = 0
while curA:
lenA += 1
curA = curA.next
while curB:
lenB += 1
curB = curB.next
curA = headA
curB = headB
if lenA >= lenB:
index = lenA-lenB
while index:
curA = curA.next
index -= 1
else:
index = lenB-lenA
while index:
curB = curB.next
index -= 1
while curA:
if curA == curB:
return curA
else:
curA = curA.next
curB = curB.next
# 142. 环形链表II
- 链接:代码随想录
- 第一想法:
判断是否有环:俩指针 一个slow 一个fast每个每次移动一位 如果fast.next = slow相遇就说明有环。但没想出来如果没环,这个循环如何停止。
- 看完代码随想录的想法:
这个数学完全没想到。关于循环如何停止:如果有环,直接return 环入口;没有环,自然可以用null停止。
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 判断是否有环
fast = head
slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
index1 = fast
index2 = head
while (index1 != index2):
index1 = index1.next
index2 = index2.next
return index2
return None