Java实现:
public class SinglyList {
private LNode list;
public LNode createByTail(int... nums) {
list = new LNode();
list.next = null;
LNode tailNode = list;
for (int i = 0; i < nums.length; i++) {
LNode newNode = new LNode();
newNode.data = nums[i];
newNode.next = null;
tailNode.next = newNode;
tailNode = newNode;
}
return list;
}
public LNode sortList() {
LNode head=list;
sort(head,null);
return head;
}
public void sort(LNode head,LNode end) {
if(head!=end) {
LNode p1=head;
LNode p2=head;
while(p2!=end) {
if(p2.data<head.data) {
p1=p1.next;
int temp=p1.data;
p1.data=p2.data;
p2.data=temp;
}
p2=p2.next;
}
if(p1!=head) {
int temp=p1.data;
p1.data=head.data;
head.data=temp;
}
sort(head,p1);
sort(p1.next,end);
}
}
public void merge(SinglyList A, SinglyList B) {
LNode aNode = A.list.next;
LNode bNode = B.list.next;
A.list.next = null;
while (aNode != null && bNode != null) {
if (aNode.data <= bNode.data) {
LNode temp = aNode.next;
aNode.next = A.list.next;
A.list.next = aNode;
aNode = temp;
}
else {
LNode temp = bNode.next;
bNode.next = A.list.next;
A.list.next = bNode;
bNode = temp;
}
}
while (aNode != null) {
LNode temp = aNode.next;
aNode.next = A.list.next;
A.list.next = aNode;
aNode = temp;
}
while (bNode != null) {
LNode temp = bNode.next;
bNode.next = A.list.next;
A.list.next = bNode;
bNode = temp;
}
}
public void print() {
LNode node = list.next;
String str = "[";
while (node != null) {
str += node.data;
if (node.next != null) {
str += ", ";
}
node = node.next;
}
str += "]";
System.out.println(str);
}
public void length() {
LNode node=list.next;
int length=0;
while(node!=null) {
node=node.next;
length ++;
}
System.out.println(length);
}
}
class LNode {
int data;
LNode next;
}
public class LinkedTest {
public static void main(String[] args) {
// 创建单链表 A
SinglyList A = new SinglyList();
A.createByTail(3,5,19,4,8);//1, 3, 5, 7, 9
System.out.println("链表一为:");
A.print();
// 创建单链表 B
SinglyList B = new SinglyList();
B.createByTail(5,10,2,7,3);//2, 4, 5
System.out.println("链表二为:");
B.print();
A.sortList();
B.sortList();
SinglyList list = new SinglyList();
list.merge(A, B);
System.out.println("新表为:");
A.print();
System.out.println("新表长度为:");
A.length();
}
结果为: