1 合并链表
//已知两个链表head1 和head2 各自从小到大有序,请把它们归并成一个链表依然从小到大有序
class Node{
int data
Node next
}
Node Merge(Node head1 , Node head2) {
//TODO
}
//使用递归的方法
public static Node Merge1(Node head1, Node head2) {
//若两个链表都为空,返回null
if (head1 == null && head2 == null) return null;
//若其中一个链表为空,返回另外一个链表
if (head1 == null) return head2;
if (head2 == null) return head1;
//判断两个链表是否相交
if (head1 == head2) {
System.out.println("两个链表相交!!!!!!!");
return null;
}
//定义一个空的链表
Node head = null;
//若head1中的当前值小于等于head2的当前值时:
// 1.把head1的赋值给head
// 2.递归调用Merge1(head1.next, head2)
//否则
// 1.把head2的赋值给head
// 2.递归调用Merge1(head1, head2.next)
if (head1.data <= head2.data) {
head = head1;
head.next = Merge1(head1.next, head2);
} else {
head = head2;
head.next = Merge1(head1, head2.next);
}
return head;
}
//常规方法
public static Node Merge2(Node head1, Node head2) {
//若两个链表都为空,返回null
if (head1 == null && head2 == null) return null;
//若其中一个链表为空,返回另外一个链表
if (head1 == null) return head2;
if (head2 == null) return head1;
//新建一个节点作为合并的节点,初始值设为-1
Node node = new Node();
node.data = -1;
//新链表的表头
Node head = node;
while (head1 != null && head2 != null) {
//判断两个链表是否相交
if (head1.equals(head2)) {
System.out.println("两个链表相交!!!!");
return null;
}
if (head1.data <= head2.data) {
node.next = head1;
head1 = head1.next;
} else {
node.next = head2;
head2 = head2.next;
}
node = node.next;
}
//把没有比较完的链表加到合并链表表尾
node.next = head1 != null ? head1 : head2;
return head.next;
}
2 多线程
2.1、吃桔子
共计9个桔子,有3个小朋友,小朋友A每次拿2个桔子,小朋友B每次拿3个桔子,小朋友C每次拿1个桔子,小朋友10s吃1个桔子,吃完后继续去拿。
小朋友每次拿桔子之前和拿了桔子之后,都会对桔子数量进行报数。如果剩余的桔子不够小朋友每次拿的数量,小朋友停止拿桔子,喊一声“不拿了”并退出游戏。
请用java多线程程序表述上面的过程。
public class EatOranges {
private static int total_oranges = 9;
public int getTotal_oranges() {
synchronized (this) {
return total_orang