设计一个带表头的双向链表(链表中数据的具体类型可以随意),提供以下方法:(1)insert:在某个位置插入对象;(2)insert:在链表的最后插入对象;(2)delete:在某个位置删除对象;(3)delete:删除链表中与x相同的元素;(4)size:返回当前链表中对象的个数;(5)isEmpty:判断链表是否为空;(6)traverse:遍历链表,打印出所有的元素;(7)getData:取得某个位置的对象。构造main函数进行测试。
public class Test {
class Node {
int data;
Node next;
Node front;
public Node() {
data = 0;
next = null;
front = null;
}
public Node(int d, Node pre, Node next) {
this.data = d;
this.front = pre;
this.next = next;
}
public void setData(int a) {
this.data = a;
}
public int getData() {
return this.data;
}
}
public int size;
public Node head;
public Node rear;
public Test() {
this.size = 0;
head = new Node();
rear = new Node(0, head, null);
head.next = rear;
}
public void insert(int e) {
Node t = new Node(e, null, null);
rear.front.next = t;
t.front = rear.front;
t.next = rear;
rear.front = t;
size++;
}
public void insert(int x, int e) {
Node t = new Node(e, null, null);
Node f = head;
for (int i = 0; i < x; i++) {
f = f.next;
}
t.next = f;
t.front = f.front;
f.front.next = t;
f.front = t;
size++;
}
public void delete(int x) {
Node f = head.next;
while (f.next != null) {
if (f.data == x) {
f.front.next = f.next;
f.next.front = f.front;
}
f = f.next;
}
}
public void delete(int pos, Test t) {
Node f = head;
for (int i = 0; i < pos; i++) {
f = f.next;
}
f.front.next = f.next;
f.next.front = f.front;
}
public boolean isEmpty() {
if (size == 0)
return true;
else
return false;
}
public int size() {
return size;
}
public void traverse() {
Node f = head.next;
while (f.next != null) {
System.out.print(f.data);
f = f.next;
}
}
public static void main(String[] args) {
Test str = new Test();
str.insert(1);
str.insert(2);
str.insert(3);
str.insert(4);
str.insert(2, 5);
str.insert(6);
System.out.println("size =" + str.size);
str.traverse();
System.out.println();
str.delete(2);
str.traverse();
System.out.println();
str.delete(3, str);
str.traverse();
}
}