单链表的增删改查 

该单链表有头节点head,其位置为0,第一个带数据的首节点位置为1

 1 public class LinkList {
 2     private class Node {
 3         int val;
 4         Node next;
 5 
 6         Node(int x) {
 7             val = x;
 8         }
 9 
10         Node() {
11         }
12     }
13 
14     private Node head = new Node();
15     public int length;//单链表的长度
16 
17     public LinkList() {
18     }
19 
20     //获取元素的值
21     public int get(int place) {
22         if (place < 0 || place > length) {
23             System.out.println("获取的位置不合法");
24         } else {
25             Node tmp = head;
26             for (int i = 0; i < place; i++) {
27                 tmp = tmp.next;
28             }
29             return tmp.val;
30         }
31         return 0;
32     }
33 
34 
35     //末尾添加元素
36     public void add(int i) {
37         Node tmp = head;
38         while (tmp.next != null) {
39             tmp = tmp.next;
40         }
41         tmp.next = new Node(i);
42         length++;
43     }
44 
45     //指定位置前添加,head除外,即从首节点开始(第一个数据节点)
46     public void insert(int place, int n) {
47         if (place < 1 || place > length) {
48             System.out.println("插入位置不合法");
49         } else {
50             Node tmp = head;
51             for (int i = 0; i < place - 1; i++) {
52                 tmp = tmp.next;
53             }
54             Node node = new Node(n);
55             node.next = tmp.next;
56             tmp.next = node;
57             length++;
58         }
59     }
60 
61     //修改指定位置的值
62     public void set(int place, int n) {
63         if (place < 1 || place > length) {
64             System.out.println("修改位置不合法");
65         } else {
66             Node tmp = head;
67             for (int i = 0; i < place; i++) {
68                 tmp = tmp.next;
69             }
70             tmp.val = n;
71         }
72     }
73 
74     //删除指定位置
75     public void delete(int place) {
76         if (place < 1 || place > length) {
77             System.out.println("删除位置不和法");
78         } else {
79             Node tmp = head;
80             for (int i = 0; i < place - 1; i++) {
81                 tmp = tmp.next;
82             }
83             tmp.next = tmp.next.next;
84             length--;
85         }
86     }
87 
88     //遍历
89     public void forSearch() {
90         Node tmp = head;
91         while (tmp.next != null) {
92             System.out.println(tmp.next.val);
93             tmp = tmp.next;
94         }
95     }
96 }