鏈表合並
阿新 • • 發佈:2017-08-29
amp string demo merge bre col pri empty listnode
1 import java.util.Stack; 2 3 class ListNode { 4 int val; 5 ListNode next = null; 6 7 ListNode(int val) { 8 this.val = val; 9 } 10 } 11 12 public class Demo03 { 13 14 public static void main(String[] args) { 15 ListNode n1 = new ListNode(10); //第一個鏈表 16 ListNode n2 = new ListNode(20); 17 ListNode n3 = new ListNode(30); 18 ListNode n4 = new ListNode(40); 19 n1.next = n2; 20 n2.next = n3; 21 n3.next = n4; 22 23 ListNode n5 = new ListNode(50); //第二個鏈表 24 ListNode n6 = newListNode(60); 25 ListNode n7 = new ListNode(70); 26 ListNode n8 = new ListNode(80); 27 n5.next = n6; 28 n6.next = n7; 29 n7.next = n8; 30 31 n1 = Merge(n1,n5); //調用合並函數 32 33 print(n1); //輸出 34 } 35 public static ListNode Merge(ListNode list1,ListNode list2) { 36 if(list1 == null && list2 == null)return null; //如果兩個鏈表都位空,則輸出空 37 if(list1 == null)return list2; //如果鏈表一為空,則合並後的鏈表即是鏈表二 38 if(list2 == null)return list1; //如果鏈表二為空,則合並後的鏈表即是鏈表三 39 Stack<Integer> stk = new Stack<Integer>(); //聲明棧 40 if(list1.val <= list2.val){ //鏈表頭部入棧 41 stk.push(list1.val); 42 stk.push(list2.val); 43 } 44 if(list1.val > list2.val){ 45 stk.push(list2.val); 46 stk.push(list1.val); 47 } 48 ListNode temp1 = list1; 49 ListNode temp2 = list2; 50 while(temp1.next != null || temp2.next != null){ 51 if(temp1.next != null && temp2.next != null){ 52 if(temp1.next.val <= temp2.next.val){ 53 stk.push(temp1.next.val); 54 stk.push(temp2.next.val); 55 } 56 if(temp1.next.val >temp2.next.val){ 57 stk.push(temp2.next.val); 58 stk.push(temp1.next.val); 59 } 60 } 61 if(temp1.next != null && temp2.next == null){ 62 stk.push(temp1.next.val); 63 } 64 if(temp1.next == null && temp2.next != null){ 65 stk.push(temp2.next.val); 66 } 67 temp1 = temp1.next; 68 temp2 = temp2.next; 69 } 70 71 int flag = 0; //將鏈表二連在鏈表一的尾部 72 ListNode temp = list1; 73 while(flag<2){ 74 if(temp.next == null){ 75 flag ++; 76 if(flag == 2)break; 77 temp.next = list2; 78 } 79 temp = temp.next; 80 } 81 list1.val = stk.pop(); //取出棧中數據,依次放入鏈接後的鏈表中 82 temp = list1.next; 83 while(!stk.isEmpty()){ 84 temp.val = stk.pop(); 85 temp = temp.next; 86 } 87 return list1; 88 89 90 } 91 92 private static void print(ListNode n) { //輸出函數 93 System.out.println(n.val); 94 if(n.next != null){ 95 print(n.next); 96 } 97 } 98 99 }
鏈表合並