Repository navigation
Expand file tree
/
Copy pathtestLinkedList.java
More file actions
113 lines (99 loc) · 2.09 KB
/
Copy pathtestLinkedList.java
File metadata and controls
113 lines (99 loc) · 2.09 KB
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
package com.shilei.test310;
import java.util.LinkedList;
public class testLinkedList <E>{
private Node first;
private Node last;
private int size;
public static void main(String[] args) {
// TODO ×Ô¶¯Éú³ÉµÄ·½·¨´æ¸ù
testLinkedList<String> tLL=new testLinkedList();
tLL.add("c0");
tLL.add("c1");
tLL.add("c2");
tLL.add("c3");
tLL.add("c4");
tLL.add("c5");
tLL.add("c6");
tLL.add("c7");
tLL.add("c8");
tLL.add("c9");
tLL.add("c10");
tLL.add("c11");
tLL.add("c12");
tLL.add("c13");
System.out.println(tLL.toString());
// tLL.remove(13);
// tLL.remove(0);
tLL.add(0, "ddd");
System.out.println(tLL.toString());
//System.out.println(tLL.get(11));
}
public Object get(int index) {
Node temp=getNode(index);
return temp.element;
}
public void add(int index,E e) {
Node temp=getNode(index);
Node node=new Node(e);
if(temp.previous==null) {
this.first=node;
temp.previous=first;
first.next=temp;
}
else {
node.previous=temp.previous;
node.next=temp;
temp.previous.next=node;
}
}
public void remove(int index) {
Node temp=getNode(index);
if(temp.previous==null) {
this.first=temp.next;
}else if(temp.next==null){
temp.previous.next=null;
}else {
temp.previous.next=temp.next;
temp.next.previous=temp.previous;
}
}
public Node getNode(int index) {
Node temp;
if(index<(size>>1)) {
temp=first;
for(int i=0;i<index;i++) {
temp=temp.next;
}
}else {
temp=last;
for(int i=size-1;i>index;i--) {
temp=temp.previous;
}
}
return temp;
}
public String toString() {
StringBuilder sB=new StringBuilder();
Node temp=first;
sB.append("[");
while(temp!=null) {
sB.append(temp.element+",");
temp=temp.next;
}
sB.setCharAt(sB.length()-1, ']');
return sB.toString();
}
public void add (E e) {
Node<E> node=new Node<E>(e);
if(first==null) {
first=node;
last=node;
}else {
node.previous=last;
node.next=null;
last.next=node;
last=node;
}
size++;
}
}