LeedCode: LinkedList

  1. Add Two Numbers
    Num 2: https://leetcode.com/problems/add-two-numbers/
    思路: 两个链表相加
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        
        if (l2 == null) {
            return l1;
        }
        
        ListNode head = new ListNode(-1);
        ListNode temp = head;
        int add = 0;
        int sub = 0;
        
        while(l1 != null && l2 != null) {
            add = (l1.val + l2.val + sub) % 10;
            sub = (l1.val + l2.val + sub)/10;
            l1.val = add;
            temp.next = l1;
            temp = temp.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        
        while(l1 != null) {
            add = (l1.val + sub) % 10;
            sub = (l1.val + sub) / 10;
            
            l1.val = add;
            temp.next = l1;
            temp = temp.next;
            l1 = l1.next;
        }
        
        while(l2 != null) {
            add = (l2.val + sub) % 10;
            sub = (l2.val + sub) / 10;
            l2.val = add;
            temp.next = l2;
            temp = temp.next;
            l2 = l2.next;
        }
        
        if (sub != 0) {
            ListNode node = new ListNode(sub);
            temp.next = node;
        }
        
        return head.next;
    }
  1. Copy List with Random Pointer
    Num 138. https://leetcode.com/problems/copy-list-with-random-pointer/
    思路:将新建的节点插入原节点后面;复制random,处理next,恢复两个新旧链表。
    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        
        Node temp = head;
        while (temp != null) {
            Node node = new Node(temp.val);
            node.next = temp.next;
            temp.next = node;
            temp = temp.next.next;
        }
        
        temp = head;
        while (temp != null) {
            if (temp.random != null) {
                temp.next.random = temp.random.next;    
            }
            temp = temp.next.next;
            
        }
        
        Node result = head.next;
        Node pold = head;
        Node pnew = result;
        while (pnew.next != null) {
            pold.next = pnew.next;
            pold = pold.next;
            pnew.next = pold.next;
            pnew = pnew.next;
        }
        
        pold.next = null;
        pnew.next = null;
        
        return result;
        
    }

你可能感兴趣的:(LeedCode: LinkedList)