java设计双向链表

49 篇文章 1 订阅
38 篇文章 5 订阅

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

}

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值