设计一个带表头的双向链表(略有修改

设计一个带表头的双向链表,要求链表中可以存放 任意类型的数据 ),提供以下方法:(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();
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值