1. 程式人生 > >Java單鏈表排序方法

Java單鏈表排序方法

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<size; 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);
				}
			}
		}
	}
}