1 package structure; 2 3 import static net.mindview.util.Print.*; 4 5 import java.util.Arrays; 6 import java.util.Scanner; 7 8 /** 9 * 单链表操作 10 * @author Tom Tao 11 * 12 */ 13 14 public class LinkedList { 15 16 public int value; 17 public LinkedList next; 18 public LinkedList(int n) { 19 this.value = n; 20 } 21 public String toString() { 22 return value + ""; 23 } 24 25 public static LinkedList head; 26 public static LinkedList t; 27 28 /*初始化*/ 29 public static void init(int nums[]) { 30 head = new LinkedList(nums[0]); 31 head.next = null; 32 t = head; 33 for(int i = 1 ; nums[i] != -1 ; i ++) { 34 LinkedList temp = new LinkedList(nums[i]); 35 t.next = temp; 36 t = temp; 37 } 38 } 39 40 /*打印链表*/ 41 public static void printList(LinkedList h) { 42 LinkedList hed = h; 43 while(hed != null) { 44 System.out.print(hed.value + " "); 45 hed = hed.next; 46 } 47 print(); 48 } 49 50 //插入操作 51 public static void insert(int index, int n) { 52 LinkedList nw = new LinkedList(n); 53 if(index == 0) { 54 nw.next = head; 55 head = nw; 56 return; 57 } 58 LinkedList p = head; 59 LinkedList temp = head; 60 for(int i = 0 ; i < index ; i ++) { 61 p = temp; 62 temp = temp.next; 63 } 64 p.next = nw; 65 nw.next = temp; 66 } 67 68 //删除操作 69 public static void delete(int index) { 70 if(index == 0) { 71 head = head.next; 72 return; 73 } 74 LinkedList p = head; 75 LinkedList temp = head; 76 for(int i = 0 ; i < index ; i ++) { 77 p = temp; 78 temp = temp.next; 79 } 80 p.next = temp.next; 81 } 82 83 //查找 84 public static void find(int index) { 85 LinkedList temp = head; 86 for(int i = 0 ; i < index ; i ++) { 87 temp = temp.next; 88 } 89 print(temp.value); 90 } 91 92 public static void main(String[] args) { 93 Scanner sc = new Scanner(System.in); 94 print("please input some numbers to init the linkedlist"); 95 int n; 96 int nums[] = new int[100]; 97 Arrays.fill(nums, -1); 98 int count = 0; 99 while((n = sc.nextInt()) != -1) { 100 nums[count ++] = n; 101 } 102 init(nums); 103 printList(head); 104 print("please input the index and value"); 105 int index = sc.nextInt(); 106 int value = sc.nextInt(); 107 insert(index, value); 108 printList(head); 109 print("please input the index to delete"); 110 index = sc.nextInt(); 111 delete(index); 112 printList(head); 113 print("please input the index to find"); 114 index = sc.nextInt(); 115 find(index); 116 sc.close(); 117 } 118 }
浙公网安备 33010602011771号