合并两个排序的链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 
 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode Merge(ListNode list1,ListNode list2) {
12         ListNode dummy = new ListNode(0);
13         ListNode p = dummy, p1 = list1, p2 = list2;
14         while (p1 != null && p2 != null) {
15             if (p1.val <= p2.val) {
16                 p.next = new ListNode(p1.val);
17                 p1 = p1.next;
18             } else {
19                 p.next = new ListNode(p2.val);
20                 p2 = p2.next;
21             }
22             p = p.next;
23         }
24         while (p1 != null) {
25             p.next = new ListNode(p1.val);
26             p = p.next;
27             p1 = p1.next;
28         }
29         
30         while (p2 != null) {
31             p.next = new ListNode(p2.val);
32             p = p.next;
33             p2 = p2.next;
34         }
35         
36         return dummy.next;
37     }
38 }

 

posted @ 2020-02-17 19:40  hyx1  阅读(99)  评论(0编辑  收藏  举报