From 5bdf84d5a8ef20a8ac34b437b2c443a1725f2c11 Mon Sep 17 00:00:00 2001 From: Shao <1504517387@qq.com> Date: Thu, 27 Jun 2019 20:42:04 +0800 Subject: [PATCH] Update LinkedListAlgo.java --- java/07_linkedlist/LinkedListAlgo.java | 95 +++++++++++++++++--------- 1 file changed, 64 insertions(+), 31 deletions(-) diff --git a/java/07_linkedlist/LinkedListAlgo.java b/java/07_linkedlist/LinkedListAlgo.java index e5fb99f..e76ced0 100644 --- a/java/07_linkedlist/LinkedListAlgo.java +++ b/java/07_linkedlist/LinkedListAlgo.java @@ -41,41 +41,74 @@ public class LinkedListAlgo { } // 有序链表合并 - public static Node mergeSortedLists(Node la, Node lb) { - if (la == null) return lb; - if (lb == null) return la; + // public static Node mergeSortedLists(Node la, Node lb) { + // if (la == null) return lb; + // if (lb == null) return la; - Node p = la; - Node q = lb; - Node head; - if (p.data < q.data) { - head = p; - p = p.next; - } else { - head = q; - q = q.next; - } - Node r = head; + // Node p = la; + // Node q = lb; + // Node head; + // if (p.data < q.data) { + // head = p; + // p = p.next; + // } else { + // head = q; + // q = q.next; + // } + // Node r = head; - while (p != null && q != null) { - if (p.data < q.data) { - r.next = p; - p = p.next; - } else { - r.next = q; - q = q.next; - } - r = r.next; + // while (p != null && q != null) { + // if (p.data < q.data) { + // r.next = p; + // p = p.next; + // } else { + // r.next = q; + // q = q.next; + // } + // r = r.next; + // } + + // if (p != null) { + // r.next = p; + // } else { + // r.next = q; + // } + + // return head; + //} + + //----------------------------------------- + + // 有序链表合并 Leetcode 21 + /** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode soldier = new ListNode(0); //利用哨兵结点简化实现难度 技巧三 + ListNode p = soldier; + + while ( l1 != null && l2 != null ){ + if ( l1.val < l2.val ){ + p.next = l1; + l1 = l1.next; + } + else{ + p.next = l2; + l2 = l2.next; + } + p = p.next; + } + + if (l1 != null) { p.next = l1; } + if (l2 != null) { p.next = l2; } + return soldier.next; } - if (p != null) { - r.next = p; - } else { - r.next = q; - } - - return head; - } // 删除倒数第K个结点 public static Node deleteLastKth(Node list, int k) {