java设计一个带表头的双向链表

class Node {
    Object msg;
    Node next,pre;
}
public class DoubleLink { //根节点的编号为零
     private Node root;
     private int  size;
	public DoubleLink() {
		root =new Node();
		root.next=null;
		root.pre=null;
		size = 0;
	}
	public boolean insert(int pos,Object val)
	{
		if (pos>size||pos<1)//可以插入到1~size的位置
			return false;
		int flag=0;
		Node tmp=root;
		while (flag<pos-1)//找到
		{
			tmp=tmp.next;
			flag++;
		}
			Node New=new Node();
			New.msg=val;
			tmp.next.pre=New;
			New.next=tmp.next;
			New.pre=tmp;
			tmp.next=New;
			size++;
			return true;
	}
	public void insert(Object val)//插到末尾
	{
		int flag=0;
		Node tmp=root;
		while (flag<size)//找到
		{
			tmp=tmp.next;
			flag++;
		}
		Node New=new Node();
		New.msg=val;
		New.next=tmp.next;
		New.pre=tmp;
		tmp.next=New;
		size++;
	}
	public boolean delete(int pos)//删除指定位置的对象
	{
		if (pos<1||pos>size)//超出范围,只能删除1~size范围的对象
			return false;
		int flag=0;
		Node tmp=root;
		while (flag<pos-1)//找到
		{
			tmp=tmp.next;
			flag++;
		}
		if (tmp.next.next!=null)
		tmp.next.next.pre=tmp;
		tmp.next=tmp.next.next;
		size--;
		return true;
	}
	public void delete(Object x)//删除值为x的所有对象
	{
		Node tmp=root;
		while (tmp.next!=null)
		{
			if (tmp.next.msg.equals(x))
			{
				if (tmp.next.next!=null)
				tmp.next.next.pre=tmp;
				tmp.next=tmp.next.next;
				size--;
			}
			tmp=tmp.next;
		}
	}
	public int size()//返回链表长度
	{
		return size;
	}
	public boolean isEmpty()//判断链表是否为空
	{
		if (size==0)
			return true;
		else
			return false;
	}
	public void traverse()//打印全部对象的值
	{
		Node tmp=root.next;
		if (tmp==null)
			System.out.print("该链表为空");
		else
			System.out.print("该链表为的内容为: ");
		while (tmp!=null)
		{
			System.out.print(tmp.msg+" ");
			//System.out.println("1");
			tmp=tmp.next;
		}
		System.out.println();
	}
	public Object getData(int pos)//返回指定位置的对象
	{
		if (pos<1||pos>size)//超出范围,只能得到1~size范围的对象
			return false;
		int flag=0;
		Node tmp=root;
		while (flag<pos)//找到pos处的对象
		{
			tmp=tmp.next;
			flag++;
		}
		return tmp.msg;
	}
     
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值