目的:将两个有序的单链表合并成一个有序的单链表
实现思路:三个节点:p=this.head;q=link.head;s=head(用于标记新节点的尾部),两个链表开始的头部value,谁小的话,就作为起始,一开始1<2,所以1为头,就让p先后移;比较p,q对应的value值,谁小,就让s连接谁,更新尾巴,同时连接到谁了就让谁往后面走;图中tail在5的位置,q在6的位置,p在9的位置,比较q,p对应的value,其中q<p,这时,让s连接6,更新tail到6的位置,同时让q向后移。只要有一方结束,就让尾巴链接到另一个链表。
public SingleLink mergeLink(SingleLink<T> link){
if(link==null || link.head==null && head==null){
return null;//如果传入的参数不合法,并且两个链表都为空,就返回出去
}
if(head==null){//如果当前链表为空的话,就让对方链表头和尾赋值为当前链表
this.head=link.head;
this.tail=link.tail;
}else if(link.head==null){
this.head=this.head;
this.tail=this.tail;
}//else if可以省略
Node<T> p=this.head,q=link.head;
//this.head更新 两个链表开始的头部value,谁小的话,就作为起始
this.head=this.head.value.compareTo(link.head.value)<0? this.head:link.head;
if (p==head){//如谁为头,谁就向后面移动一步
p=p.next;
}else {
q=q.next;
}
Node<T> s =head;//新链表尾部,作为链接动作
while(q!=null&&p!=null){
//p.value.compareTo(q.value)<0
if(p.value.compareTo(q.value)<0){//谁小,s就链接谁;连到谁之后就向后走,同时更新尾巴
s.next=p;
s=p;
p=p.next;
}else {
s.next=q;
s=q;
q=q.next;
}
}
//只要有一方结束,就让尾巴链接到另一个链表
if(p==null){
s.next=q;
}else {
s.next=p;
}
while (s.next!=null){
s=s.next;
}
this.tail=s;
return this;
}