初識資料結構之單鏈表——Java語言
阿新 • • 發佈:2018-12-09
import java.util.Scanner; public class LinkList{ ListNode H = new ListNode(0); /** *尾插法建立連結串列 */ public void creatLinkList(){ ListNode first = H; Scanner sc = new Scanner(System.in); System.out.print("輸入結點的資料:"); int x = sc.nextInt(); while(x != -1) { ListNode q = new ListNode(x); first.next = q; first = q; //first指向新的尾結點 x = sc.nextInt(); } } /** *求表長 */ public int length(){ ListNode first = H.next; int length = 0; while(first != null) { length++; first = first.next; } return length; } /** *按序號查詢 */ public ListNode get_pos(int x){ ListNode first = H.next; int pos = 0; while(first != null && pos < x - 1) { first = first.next; pos++; } if(pos == x - 1) return first; return null; } /** *按值查詢 */ public ListNode get_val(int x){ ListNode first = H.next; while(first != null && first.data != x) { first = first.next; } if(first.data == x) return first; return null; } /** *指定位置插入x */ public void insert(int pos,int x){ ListNode p = get_pos(pos - 1); if(p == null) { System.out.println("位置錯誤"); }else{ ListNode q = new ListNode(x); q.next = p.next; p.next = q; } } /** *刪除x */ public void remove(int x){ ListNode p = get_val(x); if(p == null) { System.out.println("元素不存在");; }else{ ListNode q = H.next; while(q.next != p) q = q.next; q.next = p.next; } } /** *遍歷連結串列 */ public void printLinkList(){ ListNode first = H.next; while(first != null) { if(first.next == null) System.out.println(first.data); else System.out.print(first.data + "->"); first = first.next; } } public static void main(String[] args) { LinkList L = new LinkList(); L.creatLinkList(); System.out.print("建立的連結串列為:"); L.printLinkList(); System.out.printf("表長:%d\n",L.length()); L.insert(2,20); System.out.print("插入元素後的連結串列為:"); L.printLinkList(); L.remove(99); System.out.print("刪除元素後的連結串列為:"); L.printLinkList(); } } class ListNode{ int data; ListNode next; ListNode(int data){ this.data = data; } ListNode(int data,ListNode next){ this.data = data; this.next = next; } }
結果展示:
——越努力越幸運。