实现思路
1.传入两个链表的头结点
2.新建一个链表的头结点newHead
3.循环比较传入的两个链表的排序变量,谁小(这里按从小到大安排序)谁加到newHead的后边
4.如果有一个链表已经为空,那么就只是针对另一个链表进行添加即可,知道两个链表都为空。
代码实现
public class SingleLinkedList {
private Person head = new Person(0,"");
// 添加
public void add(Person person){
Person temp = head;
// 找到最后一个再添加
while(true){
if (temp.next == null){
// 已经在最后一个了
temp.next = person;
break;
}
temp = temp.next;
}
}
// 获取头结点
public Person getHead(){
return head;
}
// 取出第n个节点
public Person getNode(Person headNode){
Person temp = headNode;
if(headNode.next == null){
throw new RuntimeException("链表为空。。。");
}
Person res = temp.next;
temp.next = temp.next.next;
res.next = null;
return res;
}
// 显示所有的节点
public void show(Person headNode){
if(headNode.next == null){
throw new RuntimeException("链表为空。。。");
}
Person temp = headNode.next;
while(true){
if(temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
public static void combineList(Person head1,Person head2){
Person temp1 = head1.next;
Person temp2 = head2.next;
Person newHead = new Person(0,"");
if(head1.next == null){
newHead.next = head2.next;
}else if (head2.next == null){
newHead.next = head1.next;
}
Person temp3 = newHead;
while(temp1 != null || temp2 != null){
if(temp1 == null && temp2 != null){
temp3.next = temp2;
temp2 = temp2.next;
}else if(temp2 == null && temp1 != null){
temp3.next = temp1;
temp1 = temp1.next;
}else {
if (temp1.id <= temp2.id) {
temp3.next = temp1;
temp1 = temp1.next;
} else {
temp3.next = temp2;
temp2 = temp2.next;
}
}
temp3 = temp3.next;
}
SingleLinkedList singleLinkedList = new SingleLinkedList();
singleLinkedList.show(newHead);
}
}
结点:
public class Person {
public int id;
public String name;
public Person next;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
测试类:
public class TestMain {
public static void main(String[] args) {
Person person1 = new Person(1,"zs");
Person person2 = new Person(3,"ls");
Person person3 = new Person(6,"ww");
SingleLinkedList single = new SingleLinkedList();
single.add(person1);
single.add(person2);
single.add(person3);
Person person4 = new Person(2,"zs2");
Person person5 = new Person(5,"ls2");
Person person6 = new Person(8,"ww2");
SingleLinkedList single2 = new SingleLinkedList();
single2.add(person4);
single2.add(person5);
single2.add(person6);
SingleLinkedList.combineList(single.getHead(),single2.getHead());
}
}