设计一个带表头的双向链表,要求链表中可以存放 任意类型的数据 ),提供以下方法:(1)insert: 在某个位置 插入对象;(2)insert:在链表的最后插入对象;(2)delete:在某个位置删除对象;(3)delete:删除链表中与x相同的元素;(4)size:返回当前链表中对象的个数;(5)isEmpty:判断链表是否为空;(6)traverse:遍历链表,打印出所有的元素;(7)getData:取得某个位置的对象。构造main函数进行测试。
package list;
public class DoublyLinkedList {
class Node {
int data;
Node next;
Node front;
public Node() {
data = 0;
next = null;
front = null;
}
public Node(int d, Node fro, Node nex) {
data = d;
front = fro;
next = nex;
}
public void setData(int a) {
data = a;
}
public int getData() {
return data;
}
}
public int size;
public Node head;
public Node rear;
public DoublyLinkedList() {
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 pos, int e) {//在pos位置处插入
Node t = new Node(e, null, null);
Node temp = head;
for (int i = 0; i < pos; i++) {
temp = temp.next;
}
t.next = temp;
t.front = temp.front;
temp.front.next = t;
temp.front = t;
size++;
}
public void deleteValue(int x) {//删除等于x的结点
Node temp = head.next;
while (temp.next != null) {
if (temp.data == x) {
temp.front.next = temp.next;
temp.next.front = temp.front;
}
temp = temp.next;
}
size--;
}
public void deletePos(int pos) {//删除第pos个结点,从1开始
Node temp = head;
for (int i = 0; i < pos; i++) {
temp = temp.next;
}
temp.front.next = temp.next;
temp.next.front = temp.front;
size--;
}
public boolean isEmpty() {
if (size == 0)
return true;
else
return false;
}
public int size() {
return size;
}
public void traverse() {
Node temp = head.next;
while (temp.next != null) {
System.out.print(temp.data);
temp = temp.next;
}
}
public static void main(String[] args) {
DoublyLinkedList str = new DoublyLinkedList();
str.insert(1);
str.insert(2);
str.insert(3);
str.insert(2, 5);
str.insert(4);
System.out.println(str.size);
str.traverse();
System.out.println();
str.deleteValue(2);
str.traverse();
System.out.println();
str.deletePos(3);
str.traverse();
}
}