两个有序链表的合并

Posted 0820LL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两个有序链表的合并相关的知识,希望对你有一定的参考价值。

已知两个链表head1和head2各自有序,请把它们合并成一个依然有序的链表。结果链表要包含head1和head2的所有节点,及节点值相同。

 1 package com;
 2 class Node{
 3     Node next = null;
 4     int data;
 5     public Node(int data){
 6         this.data = data;
 7     }
 8 }
 9 
10 public class MergeList {
11     public static Node mergeList(Node head1, Node head2){
12         if (head1 == null){
13             return head1;
14         }
15         if (head2 == null){
16             return head2;
17         }
18         Node p1 = null;
19         Node p2 = null;
20         Node head = null;
21         if (head1.data < head2.data){
22             head = head1;
23             p1 = head1.next;
24             p2 = head2;
25         } else {
26             head = head2;
27             p1 = head1;
28             p2 = head2.next;
29         }
30         Node pcur = head;
31         while (p1 != null && p2 != null) {
32             if (p1.data < p2.data) {
33                 pcur.next = p1;
34                 pcur = p1;
35                 p1 = p1.next;
36             } else {
37                 pcur.next = p2;
38                 pcur = p2;
39                 p2 = p2.next;
40             }
41         }
42             if (p1 != null){
43                 pcur.next = p1;
44             }
45             if (p2 != null){
46                 pcur.next = p2;
47             }
48         return head;
49     }
50     public static void main(String[] args){
51         Node head1 = new Node(1);
52         Node node3 = new Node(3);
53         Node node5 = new Node(5);
54         head1.next = node3;
55         node3.next = node5;
56         node5.next = null;
57         Node head2 = new Node(2);
58         Node node4 = new Node(4);
59         Node node6 = new Node(6);
60         Node node7 = new Node(7);
61         head2.next = node4;
62         node4.next = node6;
63         node6.next = node7;
64         node7.next = null;
65         Node mergeHead = mergeList(head1, head2);
66         while (mergeHead != null){
67             System.out.print(mergeHead.data + " ");
68             mergeHead = mergeHead.next;
69         }
70     }
71 }

 

以上是关于两个有序链表的合并的主要内容,如果未能解决你的问题,请参考以下文章

两个有序链表的合并

合并两个有序链表【递归、迭代】

两个有序链表的合并

代码题(14)— 合并有序链表

21. 合并两个有序链表

21. 合并两个有序链表