Java實現連結串列程式碼
阿新 • • 發佈:2018-12-11
Java實現簡練單鏈表程式碼
package 連結串列; import javax.print.attribute.standard.NumberOfDocuments; import static com.sun.tools.classfile.CharacterRangeTable_attribute.Entry.length; class Node{ Node next = null; int data; public Node(int data) { this.data = data; } } public class MyLinkedList { Node head = null; /** * 連結串列的插入 * @param d 插入連結串列的資料 */ public void addNode(int d){ //新建一個節點 Node newNode = new Node(d); //連結串列為空 if(null == head){ head = newNode; return; } //迴圈找到連結串列的末尾 Node tmp = head; while (tmp.next!=null){ tmp=tmp.next; } tmp.next = newNode; } /** * * @param index 連結串列的索引 * @return 如果索引小於1或者索引大於連結串列的長度返回false * 刪除成功返回true */ public boolean deleteNode(int index){ if(index<1||index>length()){ return false; } //特判刪除頭指標,因為單向連結串列沒有前驅節點,刪除比較簡單 if(index == 1){ head = head.next; return true; } int i=1; Node preNode = head; Node curNode = head.next; while (curNode!=null){ //找到索引的位置,將i對應的節點刪除, //i的前驅節點指向index的後繼節點(刪除第index個節點) if(i==index){ preNode.next = curNode.next; return true; } preNode = curNode; curNode = curNode.next; i++; } return true; } /** * * @return 返回連結串列的長度 */ public int length(){ int length = 0; Node tmp = head; while (tmp.next!=null){ length++; tmp = tmp.next; } return length; } /** * * @return連結串列為空返回true */ public boolean isEmpty(){ return null == head?true:false; } /** * * @return返回排好序的連結串列 */ public Node orderList(){ int tmp=0; Node curNode = head; Node nextNode = null; while (curNode.next!=null){ nextNode = curNode.next; //從小到大排序 while(nextNode!=null){ if(curNode.data > nextNode.data){ tmp = curNode.data; curNode.data = nextNode.data; nextNode.data = tmp; } nextNode = nextNode.next; } curNode = curNode.next; } return head; } /** * 輸出連結串列 */ public void printList(){ Node tmp = head; while(tmp!=null){ System.out.println(tmp.data); tmp = tmp.next; } } public static void main(String[] args) { MyLinkedList list = new MyLinkedList(); list.addNode(10); list.addNode(3); list.addNode(5); list.addNode(1); list.addNode(9); System.out.println("length is "+list.length()); System.out.println("before order"); list.printList(); list.orderList(); System.out.println("after order"); list.printList(); } }