训练营第四天 Leetcode 24 19 142 面试题 02。07

24

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode dummyhead = new ListNode(0, head);
        ListNode cur = dummyhead;

        while(cur.next != null && cur.next.next != null){
            ListNode next = cur.next;
            ListNode nextNext = cur.next.next;
            ListNode temp = cur.next.next.next;
            cur.next = nextNext;
            nextNext.next = next;
            next.next = temp;
            //cur = next;
            cur = cur.next.next;
        }
        return dummyhead.next;
    }
}

19:

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null) return head;
        ListNode dummy = new ListNode(0, head);
        ListNode fast = dummy;
        ListNode slow = dummy;
        for(int i = 0; i <= n; i++){
            fast = fast.next;
        }
        while(fast != null){
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
    }
}

面试题 02.07:

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode getA = headA;
        int countA = 0;
        ListNode getB = headB;
        int countB = 0;
        while(getA != null){
            getA = getA.next;
            countA++;
        }
        while(getB != null){
            getB = getB.next;
            countB++;
        }
        getA = headA;
        getB = headB;
        if(countA < countB){
            ListNode temp = headA;
            getA = headB;
            getB = headA;
            int temp1 = countA;
            countA = countB;
            countB = temp1;
        }
        int gap = countA - countB;
        for(int i = 0; i < gap; i++){
            getA = getA.next;
        }
        
        while(getA != null && getB != null){
            if(getA == getB){
                return getA;
            }
            getA = getA.next;
            getB = getB.next;
        }
        return null;
    }
}

142:
 

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;

        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(slow == fast){
                ListNode start = head;
                ListNode cycle = fast;
                while(start != cycle){
                    start = start.next;
                    cycle = cycle.next;
                }
                return cycle;
            }
        }
        return null;
    }

做下来感觉链表主要是思路和细节

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值