第三天:反转链表递归写法需要巩固

1.Swap Nodes in Pairs

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode first = head, second = head.next;
        head = head.next;

        while(second != null){
            ListNode third = null;
            if(second.next != null){
                third = second.next;
            }
            second.next = first;
            if(third == null || third.next == null){
                first.next = third;
                break;
            }else{
                first.next = third.next;
                first = third;
                second = third.next;
            }
        }
        return head;
    }
}

LinkedList操作题通解:把要做的操作全列出来,找出相同的部分放进循环里。之后,再处理边界条件。
不难,大清早就做出来了。相比答案还是复杂了些。有时间研究研究递归版本。

2.Remove Nth Node From End of List

 class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head.next == null) return null;
        ListNode dummy = new ListNode(0, head);
        ListNode tmp = head, tmp2 = dummy;
        for(int i = 0; i < n; ++i) tmp = tmp.next;
        while(tmp != null){
            tmp = tmp.next; tmp2 = tmp2.next;
        }
        tmp2.next = tmp2.next.next;
        return dummy.next;  //不能return head,因为head有可能被删掉了
    }
}

思路:先让它走n个,以后让慢pointer慢慢跟。

3.Intersection of Two Linked Lists

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode tmp1 = headA, tmp2 = headB;
        while(tmp1 != tmp2){
            tmp1 = tmp1 == null? headB: tmp1.next;
            tmp2 = tmp2 == null? headA: tmp2.next;
        }
        return tmp1;
    }
}

相交链表核心:两个指针分别从两个链表的头开始,向前遍历。如果其中一个走完了,那么换另一个链表继续走,直到相遇为止。
相遇之后,可能都为null(则不相交);如果都指向同一个值,就是他们相交的开始。

当然,还有笨蛋方法(但效率与此代码相同)。

  1. 先求出两个链表长度。
  2. 移动长链表,让两个链表在同一起跑线上。
  3. 同时移动两个指针,直到他们相遇/不相遇。如果不相遇,在最后return null即可。

4.Linked List Cycle II

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null) return null;
        ListNode slow = head, fast = head;
        while(true){
            slow = slow.next;
            if(fast == null || fast.next == null) return null;
            fast = fast.next.next;
            if(slow == fast) break;
        }
        fast = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}

环形链表(找出循环的开端)核心:用fast,slow两指针,fast每次走两个,slow走一个。当它们相遇时,让两指针每次挪一格。相遇的地方就是循环的开始,因为x = z(见下文)。

算法解释:见代码随想录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值