Chain exercises

 

Here's summarize feel more thoughtful questions popping

160. intersection list

The idea here is that a + b and b + a traversal time is the same, that is to say from the beginning of a linked list traversal then start traversing the first traverse end simultaneously traversing a b b from the list.

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null) return null;
        ListNode ans = null;
        ListNode pa = headA;
        ListNode pb = headB;
        while(pa != null || pb != null) {
            if(pa == null) pa = headB;
            if(pb == null) pb = headA;
            if(pa.val == pb.val && pa == pb) {
                ans = new ListNode(pa.val);
                break;
            }
            pa = pa.next;
            pb = pb.next;
        }
        return ans;
    }
}

206. reversal list

This should be the most important and basic operation of the

Recursion:

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode temp = head;
        ListNode next = head.next;
        head = reverseList(next);
        next.next = temp;
        temp.next = null;
        return head;
    }
}

Head interpolation method:

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode newhead = new ListNode(-1);
        while(head!=null) {
            ListNode next = head.next;
            head.next = newhead.next;
            newhead.next = head;
            head = next;
        }
        return newhead.next;
    }
}

2. The two numbers together

Here's a fill 0 of skills, this technique is still very important, pay attention to the final carry

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
        ListNode p = head;
        ListNode p1 = l1;
        ListNode p2 = l2;
        int c = 0;
        int sum = 0;
        ListNode temp = null;
        while(p1!=null || p2!=null) {
            int o1 = p1 != null ? p1.val : 0;
            int o2 = p2 != null ? p2.val : 0;
            sum = o1 + o2 + c;
            c = sum/10;
            temp = new ListNode(sum%10);
            p.next = temp;
            p = temp;
            p1 = p1 == null ? null : p1.next;
            p2 = p2 == null ? null : p2.next;
        }
        if(c!=0) {
            temp = new ListNode(c);
            p.next = temp;
        }
        return head.next;
    }
}

 

 

Guess you like

Origin www.cnblogs.com/mgblogs/p/11884570.html