链表

234. 回文链表 简单

    def isPalindrome(self, head: ListNode) -> bool:
        if head==None:
            return True
        #确定前半部分的开头slow
        slow,fast=head,head
        while fast.next!=None and fast.next.next!=None:
            slow=slow.next
            fast = fast.next.next
        
        # 将后半部分倒转,此时pre指向后半部分第一个节点
        p = slow.next
        pre = None
        while p:
            nxt = p.next
            p.next = pre
            pre = p
            p = nxt
        
        res = True
        first,second = head,pre
        while res and second!=None :
            if first.val==second.val:
                first,second=first.next,second.next
            else:
                res = False
        return res

21. 合并两个有序链表 简单

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 类似归并排序中的合并过程
        ListNode dummyHead = new ListNode(0);
        ListNode cur = dummyHead;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                cur = cur.next;
                l1 = l1.next;
            } else {
                cur.next = l2;
                cur = cur.next;
                l2 = l2.next;
            }
        }
        // 任一为空,直接连接另一条链表
        if (l1 == null) {
            cur.next = l2;
        } else {
            cur.next = l1;
        }
        return dummyHead.next;
    }

141. 环形链表 简单

快慢指针

    def hasCycle(self, head: ListNode) -> bool:
        if head==None or head.next==None:
            return False
        slow = head
        fast = head.next
        while slow!=fast:
            # 快指针会率先到达末位
            if fast==None or fast.next==None:
                return False
            slow = slow.next
            fast = fast.next.next
        return True

160. 相交链表 简单

双指针,两人走的长度一致,步调一致,短的先进入到下一段,如果有相交,最后一部分肯定是一样的

    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        p = headA
        q = headB
        while p!=q:   # 若是有缘,你们早晚会相遇
            p=headB if p==None else p.next     # 当你走到终点时,开始走她走过的路
            q=headA if q==None else q.next     # 当她走到终点时,开始走你走过的路
        return p
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值