//链表的结构
class LinkedList {
int data;
LinkedList next;
}
/**
*
* 合并两个排好序的链表
*
*/
public class UnionLinkList {
/**
* 建立单链表
* @param head 单链表头结点
*/
public void createLinkedList(LinkedList head) {
LinkedList cur = head;
Scanner scanner = new Scanner(System.in);
String data;
System.out.println("输入单链表结点的值,输入#结束");
while (true) {
data = scanner.next();
if (data.equals("#")) {
cur.next = null;
break;
}
LinkedList node = new LinkedList();
node.data = Integer.valueOf(data);
cur.next = node;
cur = cur.next;
}
}
/**
*
* @param a 链表a
* @param b 链表b
* @param union 合并后的链表
* @return 合并后的链表
*/
public LinkedList union(LinkedList a,LinkedList b,LinkedList union){
LinkedList pc = union = a;
LinkedList pa = a.next;
LinkedList pb = b.next;
while(pa != null && pb != null){
if(pa.data < pb.data){
pc.next = pa;
pc = pa;
pa = pa.next;
}else{
pc.next = pb;
pc = pb;
pb = pb.next;
}
if(pa != null){
pc.next = pa;
}
if(pb != null){
pc.next = pb;
}
}
return union;
}
/**
* 打印单链表
* @param head 链表头指针
*/
public void printLinkList(LinkedList head){
if(head == null || head.next == null){
return;
}
head = head.next;
while(head != null){
System.out.print(head.data+" ");
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
UnionLinkList ull = new UnionLinkList();
LinkedList pa = new LinkedList();
LinkedList pb = new LinkedList();
ull.createLinkedList(pa);
ull.createLinkedList(pb);
LinkedList union = null;
union = ull.union(pa,pb, union);
ull.printLinkList(union);
}
}
合并两个排好序的单链表
最新推荐文章于 2021-10-22 17:17:40 发布