Skip to content

Commit 41a2416

Browse files
Merge pull request #348 from Galileo-Bill/master
优化JAVA中的两个有序链表的合并
2 parents 3cf9115 + 703c651 commit 41a2416

File tree

1 file changed

+66
-33
lines changed

1 file changed

+66
-33
lines changed

java/07_linkedlist/LinkedListAlgo.java

Lines changed: 66 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -41,41 +41,74 @@ public static boolean checkCircle(Node list) {
4141
}
4242

4343
// 有序链表合并
44-
public static Node mergeSortedLists(Node la, Node lb) {
45-
if (la == null) return lb;
46-
if (lb == null) return la;
47-
48-
Node p = la;
49-
Node q = lb;
50-
Node head;
51-
if (p.data < q.data) {
52-
head = p;
53-
p = p.next;
54-
} else {
55-
head = q;
56-
q = q.next;
57-
}
58-
Node r = head;
59-
60-
while (p != null && q != null) {
61-
if (p.data < q.data) {
62-
r.next = p;
63-
p = p.next;
64-
} else {
65-
r.next = q;
66-
q = q.next;
67-
}
68-
r = r.next;
44+
// public static Node mergeSortedLists(Node la, Node lb) {
45+
// if (la == null) return lb;
46+
// if (lb == null) return la;
47+
48+
// Node p = la;
49+
// Node q = lb;
50+
// Node head;
51+
// if (p.data < q.data) {
52+
// head = p;
53+
// p = p.next;
54+
// } else {
55+
// head = q;
56+
// q = q.next;
57+
// }
58+
// Node r = head;
59+
60+
// while (p != null && q != null) {
61+
// if (p.data < q.data) {
62+
// r.next = p;
63+
// p = p.next;
64+
// } else {
65+
// r.next = q;
66+
// q = q.next;
67+
// }
68+
// r = r.next;
69+
// }
70+
71+
// if (p != null) {
72+
// r.next = p;
73+
// } else {
74+
// r.next = q;
75+
// }
76+
77+
// return head;
78+
//}
79+
80+
//-----------------------------------------
81+
82+
// 有序链表合并 Leetcode 21
83+
/**
84+
* Definition for singly-linked list.
85+
* public class ListNode {
86+
* int val;
87+
* ListNode next;
88+
* ListNode(int x) { val = x; }
89+
* }
90+
*/
91+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
92+
ListNode soldier = new ListNode(0); //利用哨兵结点简化实现难度 技巧三
93+
ListNode p = soldier;
94+
95+
while ( l1 != null && l2 != null ){
96+
if ( l1.val < l2.val ){
97+
p.next = l1;
98+
l1 = l1.next;
99+
}
100+
else{
101+
p.next = l2;
102+
l2 = l2.next;
103+
}
104+
p = p.next;
105+
}
106+
107+
if (l1 != null) { p.next = l1; }
108+
if (l2 != null) { p.next = l2; }
109+
return soldier.next;
69110
}
70111

71-
if (p != null) {
72-
r.next = p;
73-
} else {
74-
r.next = q;
75-
}
76-
77-
return head;
78-
}
79112

80113
// 删除倒数第K个结点
81114
public static Node deleteLastKth(Node list, int k) {

0 commit comments

Comments
 (0)