Day04 链表part02

1.两两交换链表中的结点

  • 注意临时节点的使用
  • 注意while的终止条件,合理利用and进行判断,假如第一个成立会判断第二个

2.删除链表的倒数第n-1个结点

  • 独立写出了需要遍历两次的代码,代码需要先确定链表的个数size,再利用size-n来循环 
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummyHead = ListNode(next = head)
        size = 0
        cur = dummyHead
        while cur.next:
            size += 1
            cur = cur.next
        cur = dummyHead
        for _ in range(size - n):
            cur = cur.next
        cur.next = cur.next.next
        return dummyHead.next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummyHead = ListNode(next = head)
        size = 0
        fast = dummyHead
        slow = dummyHead
        for i in range(n+1):
            fast = fast.next
        while fast:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return dummyHead.next

3.链表相交

感觉这个题目出的比较有歧义,写出来的答案主要是在对指针的判断是val还是其本身上有问题

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:

        curA = headA
        sizeA = 0
        while curA:
            curA = curA.next
            sizeA += 1

        curB = headB
        sizeB = 0
        while curB:
            curB = curB.next
            sizeB += 1
        
        diff = abs(sizeA - sizeB)

        curA = headA
        curB = headB
        if sizeA > sizeB:
            for i in range(diff):
                curA = curA.next
        else:
            for i in range(diff):
                curB = curB.next
        
        res = None
        while curA:
            if curA == curB:
                res = curA
                break
            curA = curA.next
            curB = curB.next
        
        return res

4.环形链表

能想到这个解法比较难

你可能感兴趣的:(代码随想录一刷,链表,数据结构)