import java.util.Scanner;
/**
* JAVA用链表实现的冒泡排序
* @author mengfeiyang
*
*/
public class ListSort {
public static void main(String[] args) {
ListClass list = new ListClass();
Scanner scan = new Scanner(System.in);
int i, size;
System.out.print("请输入链表的大小:");
size = scan.nextInt();
for(i=0; i
list.addAt(i, scan.nextInt());
}
System.out.println("链表结点一览:");
list.listAll();
list.bubbleSort();
System.out.println("排序后的链表结点一览:");
list.listAll();
}
}
/**
* 链表结点类
*/
class NodeClass{
private int data;
private NodeClass next; //链表结点的指针域,指向直接后继结点
public NodeClass(){
next = null;
}
public NodeClass(int data, NodeClass next){
this.data = data;
this.next = next;
}
public int getData(){
return this.data;
}
public void setData(int data){
this.data = data;
}
public NodeClass getNext(){
return this.next;
}
public void setNext(NodeClass next){
this.next = next;
}
}
/**
* 链表类
*/
class ListClass{
private NodeClass head = null; //头结点指针
private int size = 0;
public ListClass(){
head = new NodeClass();
size = 0;
}
//在i位置插入元素elem
public boolean addAt(int i, int elem) {
if(i < 0 || i > size){
return false;
}
NodeClass pre,curr;
int pos;
for(pre=head; i>0 && pre.getNext()!=null; i--,pre=pre.getNext());
curr = new NodeClass(elem, pre.getNext());
pre.setNext(curr);
size++;
return true;
}
public NodeClass getHead(){
return this.head;
}
public void setHead(NodeClass head){
this.head = head;
}
public int getSize(){
return this.size;
}
public boolean isEmpty(){
return (size==0);
}
public void listAll(){
for(NodeClass curr=head.getNext(); curr!=null; curr=curr.getNext()){
System.out.print(curr.getData() + "\t");
}
System.out.println();
}
public void bubbleSort(){
NodeClass p, q;
int temp;
for(p=head.getNext(); p.getNext()!=null; p=p.getNext()){
for(q=head.getNext(); q.getNext()!=null; q=q.getNext()){
if(q.getData() > q.getNext().getData()){
temp = q.getData();
q.setData(q.getNext().getData());
q.getNext().setData(temp);
}
}
}
}
}