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;
	}
     
}

你可能感兴趣的:(双向链表,java,数据结构)