合并两个有序列表,合并后依然有序
public class Test {
public static void main(String[] args) {
CatNode cat1 = new CatNode(12,"白猫","小白猫");
CatNode cat2 = new CatNode(10,"黑猫","小黑猫");
CatNode cat3 = new CatNode(20,"灰猫","小灰猫");
CatNode cat4 = new CatNode(40,"花猫","小花猫");
LinkedList lins = new LinkedList();
lins.addSort(cat4);
lins.addSort(cat3);
lins.addSort(cat1);
lins.addSort(cat2);
CatNode cat5 = new CatNode(8,"波斯猫","小白猫");
CatNode cat6 = new CatNode(14,"梨花猫","小黑猫");
CatNode cat7 = new CatNode(90,"短毛猫","小灰猫");
CatNode cat8 = new CatNode(56,"尖嘴猫","小花猫");
LinkedList lins2 = new LinkedList();
lins2.addSort(cat8);
lins2.addSort(cat5);
lins2.addSort(cat7);
lins2.addSort(cat6);
System.out.println("合并后的链表");
merge(lins,lins2).list();
}
public static LinkedList merge(LinkedList l1, LinkedList l2){
LinkedList preHead = new LinjedList();
CatNode prev = preHead.cHead;
CatNode temp1 = l1.cHead.next;
CatNode temp2 = l2.cHead.next;
while(temp1 != null && temp2 != null){
if(temp1.no <= temp2.no){
prev.next = temp1;
temp1 = temp1.next;
}else {
prev.next = temp2;
temp2 = temp2.next;
}
prev = prev.next;
}
prev.next = temp1 == null ? temp2 : temp1;
return preHead;
}
}
class LinkedList{
CatNode cHead = new CatNode(0,"","");
public void addSort(CatNode catNode){
CatNode temp = cHead;
boolean flage = false;
while(true){
if(temp.next == null){
break;
}
if(temp.next.no > catNode.no){
break;
}else if(temp.next.no == catNode.no){
flage = true;
break;
}
temp = temp.next;
}
if(flage){
System.out.println("编号为" + catNode.no + "在链表中已存在,无法插入");
}else {
catNode.next = temp.next;
temp.next = catNode;
}
}
public void list(){
if (cHead.next == null){
System.out.println("链表为空无法遍历");
return;
}
CatNode temp = cHead.next;
while(true){
if(temp == null){
break;
}
System.out.println(temp);
temp = temp.next;
}
}
}
class CatNode{
int no;
String name;
String nickName;
CatNode next;
public CatNode(int no, String name, String nickName) {
this.no = no;
this.name = name;
this.nickName = nickName;
}
@Override
public String toString() {
return "CatNode{" +
"no=" + no +
", name='" + name + '\'' +
", nickName='" + nickName + '\'' +
'}';
}
}
这种方式虽然效率没有递归高,但是便于理解。小白学韩顺平老师数据结构,有错误请各位大佬指出。
|