public class LinkListTest {
int size = 0;
Node first;
Node last;
// 添加元素
public void add(int date) {
final Node l = last;
final Node newNode = new Node(l, date, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
}
// 移除指定值得元素(如果多值相同,移除遇到的第一个)
public boolean remove(int date) {
for (Node x = first; x != null; x = x.next) {
if (date == x.date) {
final Node next = x.next;
final Node prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
size--;
return true;
}
}
return false;
}
// 移除指定位置的元素
public void removeByIndex(int index) {
remove(getElementByIndex(index));
}
// 获取数组元素个数
public int size() {
return size;
}
// 获取第一个元素
public int getFirst() {
return this.first.date;
}
// 获取最后一个元素
public int getLast() {
return this.last.date;
}
// 打印出所有元素
public void getAllElement() {
String result = "";
Node node = first;
for (int i = 0; i < size; i++) {
int temp = node.date;
node = node.next;
result += temp + " ";
}
System.out.println(result);
}
// 获取指定位置元素
public int getElementByIndex(int index) {
if (index > (size - 1)) {
new Exception("数组越界");
}
Node node = first;
int temp = 0;
for (int i = 0; i < index; i++) {
temp = node.date;
node = node.next;
if ((index - 1) == i) {
temp = node.date;
// return temp;
}
}
return temp;
}
class Node {
int date;
Node next;
Node prev;
Node(Node prev, int element, Node next) {
this.date = element;
this.next = next;
this.prev = prev;
}
}
public static void main(String[] args) {
LinkListTest linkListTest = new LinkListTest();
linkListTest.add(2);
linkListTest.add(3);
linkListTest.add(4);
// linkListTest.remove(3);
// linkListTest.remove(2);
// System.out.println(linkListTest.getFirst());
// System.out.println(linkListTest.getLast());
// System.out.println(linkListTest.size);
linkListTest.getAllElement();
System.out.println(linkListTest.getElementByIndex(2));
}
}
根据Java的源码改的链表,你最大的问题是要进行删除必须是双向链表。