合并两个有序链表,这个算法并不难,最差时间复杂度为 o(2n),需要对链表数据结构有较好的理解,则很容易完成;
思路:由于两个链表本来是有序的,所以只需要循环两个链接,比较两个链表头的大小,将较小的节点添加到新的链接表中且将该较小链表头移到下一个节点;直到有一个链接走到了头;则需要把另外一个链表添加新的链表中;
链表的定义参考百度百科链表
代码如下:
/**
* @author warlock.deng
* Created at 2021/4/22
*/
public class ListNodeMain {
public static void main(String[] args) {
ListNode one = new ListNode(3);
one.next = new ListNode(7);
one.next.next = new ListNode(10);
ListNode two = new ListNode(2);
two.next = new ListNode(4);
two.next.next = new ListNode(6);
two.next.next.next = new ListNode(9);
two.next.next.next.next = new ListNode(14);
two.next.next.next.next.next = new ListNode(15);
ListNode node = mergeListNode(one, two);
String text = "";
}
private static ListNode mergeListNode(ListNode one, ListNode two) {
//两个空判断
if (one == null) {
return two;
}
if (two == null) {
return one;
}
ListNode head = new ListNode(0);//定义一个虚拟头节点,用来存放新的链表
ListNode tem = head;//用来向前走的动态指针
//遍历两个链接,直到两个都为null
while (one != null || two != null) {
//当两个链表都不为null时,则需要比较头节点
if (one != null && two != null) {
if (one.value > two.value) {
//第一个链接表的头节点较大,则将第二个头节点放到tem的next中,且tem要向前走一步,第二个节点也得向前走一步
tem.next = two;
tem = tem.next;
two = two.next;
} else {
//如上类似的处理
tem.next = one;
tem = tem.next;
one = one.next;
}
} else {
//有一个链表已走到头了,但不知道是哪个链表,所以要分两种情况处理;把没走到头的链表添加到新链表后面,再把没走到头的链表置为null即可。
if (one != null) {
tem.next = one;
one = null;
}
if (two != null) {
tem.next = two;
two = null;
}
}
}
//返回新链表
return head.next;
}
private static class ListNode {
public ListNode(int val) {
this.value = val;
}
private ListNode prev;
private ListNode next;
private int value;
public ListNode getPrev() {
return prev;
}
public void setPrev(ListNode prev) {
this.prev = prev;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
}
ListNode为一个链表结构,这是一个双向链表;本题其实用单向链表即可完成;