本文實例為大家分享了java合并兩個排序的鏈表,供大家參考,具體內容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
/** * * 劍指offer編程題(java實現)——第16題:合并兩個排序的鏈表 * * 輸入兩個單調遞增的鏈表,輸出兩個鏈表合成后的鏈表, 當然我們需要合成后的鏈表滿足單調不減規則。 * */ public class test16 { public static listnode merge(listnode list1, listnode list2) { if (list1 == null ) { // 首先判斷是否有鏈表為空 return list2; } else if (list2 == null ) { return list1; } listnode end1 = list1; listnode end2 = list2; listnode tmp; //end1和end2分別代表兩個鏈表,tmp用于中間合成鏈表 if (end1.val > end2.val) { //把首節點小的鏈表看作end1 tmp = end1; end1 = end2; end2 = tmp; } else { } listnode newnode = end1; //用于最終返回的鏈表首節點 while (end1.next != null && end2.next != null ) { //將鏈表2中的元素插入鏈表1中合適的位置 if (end1.val <= end2.val && end1.next.val >= end2.val) { tmp = end2.next; end2.next = end1.next; end1.next = end2; end1 = end2; end2 = tmp; } else { end1 = end1.next; } } if (end1.next == null ) { //如果鏈表1到尾節點了則直接連接剩下的鏈表2中的首節點 end1.next = end2; return newnode; } else { if (end1.next != null && end2.next == null ) { //如果鏈表2到尾節點了則將鏈表2中所剩下的最后一個節點插入鏈表1 while (end2 != null ) { if (end1.val <= end2.val && end1.next.val >= end2.val) { end2.next = end1.next; end1.next = end2; break ; } else { end1 = end1.next; if (end1.next == null ) { //鏈表2最后的節點最大 end1.next = end2; break ; } } } } return newnode; } } public static void main(string[] args) { listnode list1 = new listnode( 1 ); list1.next = new listnode( 3 ); list1.next.next = new listnode( 5 ); listnode list2 = new listnode( 2 ); list2.next = new listnode( 4 ); list2.next.next = new listnode( 6 ); system.out.println(merge(list2, list1)); } // 鏈表 public static class listnode { int val; listnode next = null ; listnode( int val) { this .val = val; } } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/as1072966956/article/details/83028219