单向链表:
package com.test.linkedlist;
public class SingleLinkedList {
private Node root;
// 向链表中添加一个结点
public void add(Object obj) {
Node node = new Node(obj);
if (root == null) {
root = node;
return;
} else {
Node n = root;
while (n.next != null) {
n = n.next;
}
n.next = node;
}
}
// 向链表中删除一个结点
public void delete(int index) {
if (index == 0) {
root = root.next;
return;
} else {
int i = 0;
Node n = root;
while (n.next != null) {
i++;
if (i == index) {
n.next = n.next.next;
return;
}
n = n.next;
}
}
}
public void display() {
for (Node n = root; n != null; n = n.next) {
System.out.print(n.value + " ");
}
System.out.println();
}
}
class Node {
Object value;
Node next;
public Node(Object value) {
this.value = value;
}
}
测试函数:
package com.test.linkedlist;
public class SingleLinkedListTest {
public static void main(String[] args) {
SingleLinkedList singleLinkedList = new SingleLinkedList();
singleLinkedList.add("a");
singleLinkedList.add("b");
singleLinkedList.add("c");
singleLinkedList.add("d");
singleLinkedList.display();
singleLinkedList.delete(3);
singleLinkedList.display();
}
}
双向链表:
package com.test.linkedlist;
public class DoubleLinkedList {
private DoubleNode root;
// 向双链表中添加结点
public void add(Object obj) {
DoubleNode node = new DoubleNode(obj);
if (root == null) {
root = node;
return;
} else {
DoubleNode n = root;
while (n.next != null) {
n = n.next;
}
n.next = node;
node.pre = n;
}
}
// 向双链表中删除结点
public void delete(int index) {
if (index == 0) {
root = root.next;
root.pre = null;
return;
} else {
DoubleNode n = root;
int i = 0;
while (n.next != null) {
i++;
if (i == index) {
if (n.next.next != null) {
n.next.next.pre = n;
}
n.next = n.next.next;
return;
}
n = n.next;
}
}
}
public void display() {
for (DoubleNode n = root; n != null; n = n.next) {
System.out.print(n.value + " ");
}
System.out.println();
}
}
class DoubleNode {
Object value;
DoubleNode pre;
DoubleNode next;
public DoubleNode(Object value) {
this.value = value;
}
}
测试函数:
package com.test.linkedlist;
public class DoubleLinkedListTest {
public static void main(String[] args) {
DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
doubleLinkedList.add("a");
doubleLinkedList.add("b");
doubleLinkedList.add("c");
doubleLinkedList.add("d");
doubleLinkedList.display();
doubleLinkedList.delete(3);
doubleLinkedList.display();
}
}