C语言能做的,Java照样可以做。但是没有指针的操作,可能使人看起来“不舒服”。这个博客是为了个人学习算法和数据结构而开的,以后凡是涉及到这方面的内容,我会尽量用Java和C同时实现。大家一起学习,共同进步。
以下为Java源码:
import java.util.Scanner;
//节点类声明
class Node {
int
data;
Node
next;
}
public class Linklist {
public
static void main(String args[]) {
Node la, lb, lc;
la = creat_list(5);
lb = creat_list(4);
lc = la;
merge_list(la, lb, lc);
print_list(lc);
}
// 链表创建方法
static Node
creat_list(int n) {
int i = 0;
Node p, head;
head = new Node();
head.next = null;
for (i = n; i > 0; i--) {
p = new Node();
System.out.println("input the
value:");
Scanner scn = new Scanner(System.in);
p.data = scn.nextInt();
p.next = head.next;
head.next = p;
}
return head;
}
static void merge_list(Node la, Node lb, Node lc) {
Node pa, pb, pc;
pa = la.next;
pb = lb.next;
pc = lc;
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;
}
}
pc.next = (pa==null)?pa:pb;
}
// 链表打印输出方法
static void
print_list(Node head) {
Node p;
p = head.next;
while (p != null) {
System.out.println("[" + p.data +
"]");
p = p.next;
}
}
}