1 public class LinkNode {
2 public String data;
3 public LinkNode next;
4
5 LinkNode(){
6 this.data = "a";
7 this.next = null;
8 }
9
10 LinkNode(String string){
11 this.data = string;
12 this.next = null;
13 }
14 }
1 public class LinkList {
2
3 public LinkNode head = null;//头指针
4 private LinkNode currentNode = null;//遍历用节点
5
6 LinkList(){}
7 LinkList(int n){
8 for(int i = 0; i<n; i++){
9 add();
10 }
11 }
12
13 public int getLength(){
14 if(head == null){
15 return 0;
16 }
17 else{
18 currentNode = head;
19 int count = 0;
20 while(currentNode != null){
21 currentNode = currentNode.next;
22 count++;
23 }
24 return count;
25 }
26 }
27
28 //头插法添加节点
29 public void add(){
30 LinkNode tempNode = new LinkNode();
31 tempNode.next = head;
32 head= tempNode;
33 }
34
35 //在第i个节点之后插入新节点
36 public void insert(int i,String string){
37 if(getLength() >= i){
38 LinkNode tempNode = new LinkNode(string);
39 if(i == 0){ //头指针后插入节点
40 tempNode.next = head;
41 head = tempNode;
42 }
43 else{
44 currentNode = head;
45 if(i == 1){ //第一个节点后插入
46 tempNode.next = currentNode.next;
47 currentNode.next = tempNode;
48 }
49 else{ //一般位置插入
50 for(int j =0; j < (i-1); j++){
51 currentNode = currentNode.next;
52 }
53 tempNode.next = currentNode.next;
54 currentNode.next = tempNode;
55 }
56 }
57 }
58 else{
59 System.out.println("要插入的位置不存在");
60 }
61 }
62
63 //删除第i个节点
64 public void delete(int i){
65 if((getLength()>=i) && (i>0)){
66 currentNode = head;
67 if(i == 1){
68 head = currentNode.next;
69 }
70 else{
71 for(int j = 1; j<(i-1); j++){
72 currentNode = currentNode.next;
73 }
74 LinkNode tempNode = currentNode.next;
75 currentNode.next = tempNode.next;
76 }
77 }
78 else{
79 System.out.println("这个节点不存在");
80 }
81 }
82
83 //修改第i个节点
84 public void modify(int i,String string){
85 if(getLength()>=i && (i>0)){
86 currentNode = head;
87 for(int j = 1; j<i; j++){
88 currentNode = currentNode.next;
89 }
90 currentNode.data = string;
91 }
92 else{
93 System.out.println("这个节点不存在");
94 }
95 }
96
97 //查询第i个节点
98 public String search(int i){
99 if(getLength()>=i && (i>0)){
100 currentNode = head;
101 for(int j = 1; j<i; j++){
102 currentNode = currentNode.next;
103 }
104 return currentNode.data;
105 }
106 else{
107 System.out.println("这个节点不存在");
108 return null;
109 }
110 }
111
112 public void display(){
113 currentNode = head;
114 while(currentNode != null){
115 System.out.println(currentNode.data.toString());
116 currentNode = currentNode.next;
117 }
118 }
119
120 public static void main(String args[]){
121 //测试代码
122 /*LinkList ll = new LinkList(4);
123 ll.insert(4, "n");
124 ll.display();
125 System.out.println(ll.getLength());
126 ll.delete(5);
127 ll.display();
128 ll.insert(4, "v");
129 System.out.println(ll.search(5));*/
130 }
131 }
JAVA 实现单链表
时间: 2024-10-07 18:34:02