java 連結串列的氣泡排序,排序之後連結串列的結構是已經發生變化的,可以直接根據head+temp +next節點列印全部
阿新 • • 發佈:2018-11-03
package interview.datastructure; /** * 實現連結串列的插入和刪除結點的操作 */ public class Link_list { //定義一個結點 class Node { Node next = null; int date; public Node(int date) { this.date = date; } } Node head = null; public void addNode(int d) { Node newNode = new Node(d); if (head == null) { head = newNode; return; } Node temp = head; //迴圈遍歷到連結串列的尾部,將資料結點插入到連結串列的尾部 while (temp.next != null) { temp = temp.next; } temp.next = newNode; } //刪除結點 public Boolean deleteNode(int index) { if (index < 1 || index > length()) return false; if (index == 1) { head = head.next; return true; } int i = 2; Node preNode = head; Node curNode = preNode.next; while (curNode != null) { if (i == index) { preNode.next = curNode.next; return true; } preNode = curNode; curNode = curNode.next; i++; } return true; } public int length() { int length = 0; Node temp = head; while (temp != null) { length++; temp = temp.next; } return length; } //氣泡排序已經改變了原來的連結串列的結構 public Node orderList() { Node nextNode = null; int temp = 0; Node curNode = head; while (curNode.next != null) { nextNode = curNode.next; while (nextNode != null) { if (curNode.date > nextNode.date) { temp = curNode.date; curNode.date = nextNode.date; nextNode.date = temp; } nextNode = nextNode.next; } curNode = curNode.next; } return head; } public void printList() { Node temp = head; while (temp != null) { System.out.println(temp.date); temp = temp.next; } } public static void main(String[] args) { Link_list lik = new Link_list(); lik.addNode(3); lik.addNode(1); lik.addNode(6); lik.addNode(2); System.out.println(lik.length()); System.out.println("排序前:"); lik.printList(); System.out.println("排序後:"); lik.orderList(); lik.printList(); }}