链表代码已给出,不知如何将冒泡排序加入下列链表中,请教了!
import java.util.Scanner;
public class work2 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
Linked linked1 = new Linked();
Linked linked2 = new Linked();
Linked linked3 = new Linked();
System.out.print("输入链表-1的大小:");
int size_1 = scanner.nextInt();
System.out.print("输入链表-2的大小:");
int size_2 = scanner.nextInt();
System.out.println("链表-1:");
for (int i = 0; i<size_1 ; i++){
int item = scanner.nextInt();
linked1.add(item);
}
System.out.println("链表-2:");
for (int i = 0 ; i<size_2 ; i++){
int item = scanner.nextInt();
linked2.add(item);
}
linked1.print("查看链表-1:");
linked2.print("查看链表-2:");
//连接两个链表
Node head1 = linked1.getFirst(); //获取链表1的头节点
Node head2 = linked2.getFirst(); //获取链表2的头节点
linked3.link(head1,head2); //连接链表方法2(具体实现)
/*
连接链表方法2
while (head1!=null){ //从链表1中逐个取出数据,逐个将数据加入到链表3中
linked3.add(head1.item);
head1 = head1.next;
}
while (head2!=null){
linked3.add(head2.item);
head2 = head2.next;
}
*/
linked3.print("查看链表1和链表2的合并最终结果:");
linked3.sort(linked3.getFirst());
}
}
//声明一个节点 (用于单链表的节点)
class Node{
int item; //整数
Node next; //指针
public Node(int item,Node next){
this.item = item;
this.next = next;
}
}
class Linked{
private Node first; //头指针
private Node last; //尾指针
//加入数据(尾插法)
public void add(int item){
Node temp = last; //临时保存当前的尾节点
Node newNode = new Node(item,null); //创建一个新的节点
last = newNode; //让新来的节点变成尾节点
if (temp==null){ //判断当前链表是否为空
first = newNode;
}else {
temp.next = newNode;
}
}
//查看当前链表的信息
public void print(String text){
System.out.print(text+"[ ");
Node print = first;
StringBuffer string = new StringBuffer();
while (print!=null){
string.append(print.item);
string.append(", ");
print=print.next;
}
string.deleteCharAt(string.length()-2);
System.out.println(string+"]\n" +text +"[头节点为->"+first.item+"] [尾节点为->"+last.item+"]");
System.out.println("--------------------------------------");
}
//排序(冒泡排序)
public Node sort(Node head){
}
//查看排序结果
private void show(Node n,int count){
System.out.println("查看排序结果:");
Node node = n.next ;
System.out.print("第"+count+"次排序:");
System.out.print("[ ");
while (node!=null){
System.out.print(node.item+" ");
node = node.next;
}
System.out.print("]");
System.out.println();
}
//获取头节点
public Node getFirst() {
return first;
}
//获取尾节点
public Node getLast(){
return last;
}
//连接两个链表(链表1的尾指针指向链表2的头指针)
public void link(Node first1 ,Node first2){
this.first = first1; //将链表1的头节点的引用赋值给当前链表头节点
Node node = this.first;
while (node.next!=null){ //找链表1的尾节点
node = node.next;
}
node.next = first2; //将链表2的头节点的引用赋值给当前链表尾节点
Node n = first2;
while (n.next!=null){ //找链表2的尾节点
n = n.next;
}
this.last = n; //令链表2的尾节点等于当前链表的尾节点
}
}