手写LinkedList(简易版)

MyLinked代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package com.lhb.test;

/**
* @Program: netty-chat
* @Description:
* @Author: LHB
* @Version: v0.0.1
* @Time: 2021-11-01 09:43
**/
public class MyLinked {

private Node head;
private volatile int length = 0;

public MyLinked() {
this.head = new Node();
}

public void addFirst(int data) {
Node node = new Node(data);
node.next = head;
head = node;
this.incrLength();
}

public void add(int data) {
Node temp = head;
while(temp.next != null) {
temp = temp.next;
}
temp.next = new Node(data);
this.incrLength();
}

public void insert(int loc, int data) {
if (loc < length) {
Node temp = head;
while(loc-1 > 0) {
temp = temp.next;
loc--;
}
Node node = new Node(data);
node.next = temp.next;
temp.next = node;
this.incrLength();
} else if(loc <= 1) {
this.addFirst(data);
} else if (loc > length) {
this.add(data);
}
}

public void update(int loc, int data) {
if (loc < length) {
Node temp = head;
while(loc > 0) {
temp = temp.next;
loc--;
}
temp.data = data;
}
}

public void delete(int loc) {
if (loc < length) {
Node temp = head;
while (loc-1 > 0) {
temp = temp.next;
loc--;
}
temp.next = temp.next.next;
this.subLength();
}
}

private synchronized void incrLength() {
this.length++;
}

private synchronized void subLength() {
this.length--;
}

public String toString() {
return "{length : "+this.length + ", head: "+ head.toString()+"}";
}

class Node {
private int data;
private Node next;
public Node() {
this.data = 0;
this.next = null;
}
public Node(int data) {
this.data = data;
this.next = null;
}

public Node(int data, Node next) {
this.data = data;
this.next = next;
}

public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{");
stringBuilder.append("data: " + data);
stringBuilder.append(", ");
stringBuilder.append("next: ");
stringBuilder.append(next == null ? "null" : next.toString());
stringBuilder.append("}");
return stringBuilder.toString();
}
}
}

Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.lhb.test;

/**
* @Program: netty-chat
* @Description:
* @Author: LHB
* @Version: v0.0.1
* @Time: 2021-11-01 09:50
**/
public class LinkedMain {
public static void main(String[] args) {
MyLinked myLinked = new MyLinked();
myLinked.addFirst(5);
myLinked.addFirst(-1);
myLinked.add(1);
myLinked.add(2);
myLinked.add(3);
myLinked.insert(2,6);
myLinked.insert(3,10);
myLinked.update(3,20);
myLinked.delete(2);
System.out.println(myLinked.toString());
}
}

输出结果:

结果

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!

请我喝杯咖啡吧~

支付宝
微信