码迷,mamicode.com
首页 > 其他好文 > 详细

两个有序链表的合并

时间:2018-09-20 11:19:05      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:data   code   节点   pac   ack   com   div   void   system   

已知两个链表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 }

 

两个有序链表的合并

标签:data   code   节点   pac   ack   com   div   void   system   

原文地址:https://www.cnblogs.com/0820LL/p/9678503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!