备战校招——单链表
思路简单,注意点是对边界的控制,即对链表最顶端和最尾端的操作。
直接上干货吧,Resource Code.....:
1 public class linklist {
2
3 public static void main(String[] argv){
4
5 Link test = new Link();
6 test.add(5);
7 test.Scan();
8 test.add(4);
9 test.Scan();
10 test.add(3);
11 test.Scan();
12 test.add(2);
13 test.Scan();
14 test.add(1);
15 test.delete_k(4);
16 test.Scan();
17 test.delete_k(6);
18 test.Scan();
19 test.delete_N(3);
20 test.Scan();
21 test.delete_N(5);
22 test.Scan();
23 }
24 }
25
26 class Link{
27 int length;
28 Link_node First;
29
30 public Link(){
31 length=0;
32 First = null;
33 }
34
35 public void delete_k(int k){
36 if(length==0){
37 System.out.println(" Link Null Error ");
38 return ;
39 }
40 Link_node temp=First;
41 Link_node temp_P=null;
42 for(int i=1; i<=length;i++ ){
43 if(temp.k==k){
44 if(i==1){
45 First=First.next;
46 length--;
47 System.out.println("Delete "+k+" Success !!!");
48 return;
49 }
50 else{
51 temp_P.next=temp.next;
52 length--;
53 System.out.println("Delete "+k+" Success !!!");
54 return;
55 }
56 }
57 temp_P=temp;
58 temp=temp.next;
59 }
60 System.out.println("Link not found "+k+" you want delete !!!");
61 }
62 public void delete_N(int n){
63 if(n<1||n>length){
64 System.out.println("delete error for n<0 or n>length !!!");
65 return;
66 }
67
68 if(n==1){
69 First=First.next;
70 length--;
71 System.out.println("Delete the "+n+"th member Success !!!");
72 return;
73 }
74 else{
75 Link_node temp=First;
76 for(int i=1;i<n-1;){
77 temp=temp.next;
78 i++;
79 }
80 temp.next=temp.next.next;
81 length--;
82 System.out.println("Delete the "+n+"th member Success !!!");
83 }
84
85
86 }
87 public void Scan(){
88 Link_node temp=First;
89 for(int i=0;i<length;i++){
90 System.out.print(" "+temp.k);
91 temp=temp.next;
92 }
93 System.out.println(" PRINT END");
94 }
95 public void add(int k){
96 add(k,length+1);
97 }
98 public void add(int key,int n ){
99
100 if(length<n-1||n<0){
101 System.out.println("add error !!!");
102 return;
103 }
104 Link_node Node = new Link_node(key);
105 if(n==1){
106 Node.next=First;
107 First=Node;
108 length++;
109 System.out.println("Add "+key+" Success !!!");
110 return;
111 }
112 Link_node temp=First;
113 for(int i=2;i<n;i++){
114 temp=temp.next;
115 }
116 Node.next=temp.next;
117 temp.next=Node;
118 length++;
119 System.out.println("Add "+key+" Success !!!");
120 }
121
122 }
123 class Link_node{
124 public int k;
125 Link_node next;
126 public Link_node(int i){
127 k=i;
128 next=null;
129 }
130 }
测试效果:
Add 5 Success !!!
5 PRINT END
Add 4 Success !!!
5 4 PRINT END
Add 3 Success !!!
5 4 3 PRINT END
Add 2 Success !!!
5 4 3 2 PRINT END
Add 1 Success !!!
Delete 4 Success !!!
5 3 2 1 PRINT END
Link not found 6 you want delete !!!
5 3 2 1 PRINT END
Delete the 3th member Success !!!
5 3 1 PRINT END
delete error for n<0 or n>length !!!
5 3 1 PRINT END