# 數據結構與算法（四）鏈表（五）- 兩個有序鏈表合併+尋找中間節點

``````public class CombineLinkedList {

@Test
public void test() {
System.out.println("------------------------------");
list.insert(0);
list.insert(1);
list.insert(3);
list.insert(5);
list.insert(7);
list.insert(9);
list.insert(10);
list.insert(11);
target.insert(2);
target.insert(4);
target.insert(6);
target.insert(8);
target.insert(10);
target.show();
System.out.println("------------------------------");
System.out.println("------------------------------ list中間節點的值是" + list.findCenter());
System.out.println("------------------------------ target中間節點的值是" + target.findCenter());
System.out.println("------------------------------");
while (current != null) {
target.insertSorted(current.data);
current = current.next;
}
target.show();
System.out.println("------------------------------");
}

class Node {
int data;
Node next;

Node(int data) {
this.data = data;
}
}

int size = 0;

public int insert(int data) {
Node temp = new Node(data);
return ++size;
}
while (current.next != null) {
current = current.next;
}
current.next = temp;
return ++size;
}

public int insertSorted(int data) {
Node temp = new Node(data);
return ++size;
}
//插到頭結點前面
return ++size;
}
while (current.next != null) {
if (temp.data >= current.data && temp.data <= current.next.data) {
//當大於等於當前節點並小於等於下一個節點時就插在這兩個節點中間
temp.next = current.next;
current.next = temp;
return ++size;
}
//list沒有比當前值更大的節點，插在末尾
current = current.next;
}
current.next = temp;
return ++size;
}

public void show() {
while (current != null) {
System.out.println("" + current.data);
current = current.next;
}
}

public int findCenter() {
int center;
if (size % 2 == 0) {
//偶數情況,要的是中間點前面那個數字
center = size / 2 - 1;
} else {
//奇數情況
center = size / 2;
}

for (int i = 0; i < center; i++) {
current = current.next;
}

return current.data;
}
}``````