标签:turn index lis -- 查找 print val lin []
1 package structure; 2 3 import java.util.Arrays; 4 import java.util.Scanner; 5 import static net.mindview.util.Print.*; 6 7 /** 8 * 双向链表的操作 9 * @author Tom Tao 10 * 11 */ 12 class Node { 13 public int value; 14 public Node(int n) { 15 this.value = n; 16 } 17 Node pre; 18 Node next; 19 } 20 21 public class ReLinkedList { 22 public static Node head; 23 public static int nodeNum; 24 25 /*初始化*/ 26 public static void init(int n[]) { 27 head = new Node(n[0]); 28 Node temp = null; 29 head.pre = null; 30 Node p = head; 31 nodeNum ++; 32 for(int i = 1 ; n[i] != -1 ; i ++) { 33 nodeNum ++; 34 temp = new Node(n[i]); 35 p.next = temp; 36 temp.pre = p; 37 p = temp; 38 } 39 p.next = null; 40 } 41 42 /*打印*/ 43 public static void printList(Node h) { 44 while(h != null) { 45 printnb(h.value + " "); 46 h = h.next; 47 } 48 } 49 50 /*插入*/ 51 public static void insert(int index, int v) { 52 Node ne = new Node(v); 53 if(index == 0) { 54 ne.next = head; 55 ne.pre = null; 56 head = ne; 57 return; 58 } 59 Node temp = head; 60 Node t = temp; 61 for(int i = 0 ; i < index ; i ++) { 62 t = temp; 63 temp = temp.next; 64 } 65 if(index == nodeNum) { 66 t.next = ne; 67 ne.pre = t; 68 ne.next = null; 69 return; 70 } 71 ne.next = temp; 72 ne.pre = t; 73 temp.pre = ne; 74 t.next = ne; 75 } 76 77 /*删除*/ 78 public static void delete(int index) { 79 if(index == 0){ 80 head = head.next; 81 head.pre = null; 82 return; 83 } 84 Node temp = head; 85 Node t = temp; 86 for(int i = 0 ; i < index ; i ++) { 87 t = temp; 88 temp = temp.next; 89 } 90 if(index == nodeNum) { 91 t.next = null; 92 return; 93 } 94 t.next = temp.next; 95 temp.next.pre = t; 96 } 97 98 /*查找*/ 99 public static int find(int index) { 100 Node temp = head; 101 for(int i = 0 ; i < index ; i ++) { 102 temp = temp.next; 103 } 104 return temp.value; 105 } 106 107 /*test*/ 108 public static void main(String[] args) { 109 Scanner sc = new Scanner(System.in); 110 print("please input the nums to init:"); 111 int[] n = new int[100]; 112 Arrays.fill(n, -1); 113 int val; 114 int count = 0; 115 while((val = sc.nextInt()) >= 0) { 116 n[count++] = val; 117 } 118 init(n); 119 while(true){ 120 printList(head); 121 print("\nplease input the index and num to insert"); 122 int index = sc.nextInt(); 123 val = sc.nextInt(); 124 insert(index, val); 125 printList(head); 126 print("\nplease input the index to delete"); 127 index = sc.nextInt(); 128 delete(index); 129 printList(head); 130 print("\nplease input the index to find"); 131 index = sc.nextInt(); 132 print(find(index)); 133 print("----------------------------------------------------"); 134 } 135 } 136 }
标签:turn index lis -- 查找 print val lin []
原文地址:http://www.cnblogs.com/tomtao/p/6599025.html