File tree Expand file tree Collapse file tree
src/main/java/com/crossoverjie/algorithm Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .crossoverjie .algorithm ;
2+
3+ /**
4+ * Function: 合并两个排好序的链表
5+ *
6+ * 每次比较两个链表的头结点,将较小结点放到新的链表,最后将新链表指向剩余的链表
7+ *
8+ * @author crossoverJie
9+ * Date: 07/12/2017 13:58
10+ * @since JDK 1.8
11+ */
12+ public class MergeTwoSortedLists {
13+
14+
15+ /**
16+ * 1. 声明一个头结点
17+ * 2. 将头结点的引用赋值给一个临时结点,也可以叫做下一结点。
18+ * 3. 进行循环比较,每次都将指向值较小的那个结点(较小值的引用赋值给 lastNode )。
19+ * 4. 再去掉较小值链表的头结点,指针后移。
20+ * 5. lastNode 指针也向后移,由于 lastNode 是 head 的应用,这样可以保证最终 head 的值是往后更新的。
21+ * 6. 当其中一个链表的指针移到最后时跳出循环。
22+ * 7. 由于这两个链表已经是排好序的,所以剩下的链表必定是最大的值,只需要将指针指向它即可。
23+ * 8. 由于 head 链表的第一个结点是初始化的0,所以只需要返回 0 的下一个结点即是合并了的链表。
24+ * @param l1
25+ * @param l2
26+ * @return
27+ */
28+ public ListNode mergeTwoLists (ListNode l1 , ListNode l2 ) {
29+ ListNode head = new ListNode (0 ) ;
30+ ListNode lastNode = head ;
31+
32+ while (l1 != null && l2 != null ){
33+ if (l1 .currentVal < l2 .currentVal ){
34+ lastNode .next = l1 ;
35+ l1 = l1 .next ;
36+ } else {
37+ lastNode .next = l2 ;
38+ l2 = l2 .next ;
39+ }
40+ lastNode =lastNode .next ;
41+ }
42+
43+ if (l1 == null ){
44+ lastNode .next = l2 ;
45+ }
46+ if (l2 == null ){
47+ lastNode .next = l1 ;
48+ }
49+
50+ return head .next ;
51+ }
52+
53+
54+ public static class ListNode {
55+ /**
56+ * 当前值
57+ */
58+ int currentVal ;
59+
60+ /**
61+ * 下一个节点
62+ */
63+ ListNode next ;
64+
65+ ListNode (int val ) {
66+ currentVal = val ;
67+ }
68+
69+ @ Override
70+ public String toString () {
71+ return "ListNode{" +
72+ "currentVal=" + currentVal +
73+ ", next=" + next +
74+ '}' ;
75+ }
76+ }
77+
78+ }
You can’t perform that action at this time.
0 commit comments