單鏈表冒泡排序

/**
* 鏈表結點類
*/
class Node{
private int data;
private Node next; //鏈表結點的指針域,指向直接後繼結點

public Node(){
next = null;
}

public Node(int data, Node next){
this.data = data;
this.next = next;
}

public int getData(){
return this.data;
}

public void setData(int data){
this.data = data;
}

public Node getNext(){
return this.next;
}

public void setNext(Node next){
this.next = next;
}
}

/**
* 鏈表類
*/
class LinkList{
private Node head = null; //頭結點指針
private int size = 0;

public LinkList(){
head = new Node();
size = 0;
}

//在i位置插入元素elem
public boolean addAt(int i, int elem) {
if(i < 0 || i > size){
return false;
}

Node pre,curr;
int pos;
for(pre=head; i>0 && pre.getNext()!=null; i--,pre=pre.getNext());
curr = new Node(elem, pre.getNext());
pre.setNext(curr);
size++;
return true;
}

public Node getHead(){
return this.head;
}

public void setHead(Node head){
this.head = head;
}

public int getSize(){
return this.size;
}

public boolean isEmpty(){
return (size==0);
}

public void listAll(){
for(Node curr=head.getNext(); curr!=null; curr=curr.getNext()){
System.out.print(curr.getData() + "\t");
}
System.out.println();
}

public void bubbleSort(){
Node 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);
}
}
}
}
}

運行測試:
請輸入鏈表的大小:4
1
2
4
3
鏈表結點一覽:
1 2 4 3
排序後的鏈表結點一覽:
1 2 3 4
發佈了88 篇原創文章 · 獲贊 18 · 訪問量 76萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章