java实现双向链表

public class HWEDLLNode {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		DLLNode onenode=new DLLNode(1);
		DLLNode twonode=new DLLNode(2);
		DLLNode threenode=new DLLNode(3);
		DLLNode fournode=new DLLNode(4);
		DLLNodeListAdd(onenode, twonode, 1);
		DLLNodeListAdd(twonode, threenode, 2);
		DLLNodeListAdd(twonode, fournode, 2);
		DLLNode currentnode=twonode;
		for(int i=0;i<DLLNodeListLength(twonode);i++)
		{
			System.out.println(currentnode.GetData());
			currentnode=currentnode.GetDLLNextNode();
		}
	}
	static int DLLNodeListLength(DLLNode headnode)
	{
		int size=1;
		if(headnode==null)
			return 0;
		else {
			DLLNode miDllNode=headnode;
			while(miDllNode.GetDLLNextNode()!=null)
			{
				miDllNode=miDllNode.GetDLLNextNode();
				size++;
			}
		}
		return size;
	}
	static DLLNode DLLNodeListAdd(DLLNode headnode,DLLNode insertnode,int position)
	{
		int size=DLLNodeListLength(headnode);
		if(size==0)
			return headnode;
		if(position>size+1||position<1)
		{
			System.out.println("Position of node is invalid");
			return headnode;
		}
		else {
			DLLNode currentnode=headnode;
			if(position==1)
			{
				insertnode.SetDLLNextNode(currentnode);
				currentnode.SetDLLPreviousNode(insertnode);
				insertnode.SetDLLPreviousNode(null);
				return insertnode;
			}
			else {
				DLLNode cDllNode=headnode;
				int count=1;
				while(count<position)
				{
					cDllNode=cDllNode.GetDLLNextNode();
					count++;
				}
				if(cDllNode.GetDLLNextNode()==null)
				{
					insertnode.SetDLLNextNode(null);
					cDllNode.SetDLLNextNode(insertnode);
					insertnode.SetDLLPreviousNode(cDllNode);
				}			
				else {
					insertnode.SetDLLNextNode(cDllNode.GetDLLNextNode());
					cDllNode.SetDLLPreviousNode(insertnode);
					cDllNode.SetDLLNextNode(insertnode);
					insertnode.SetDLLPreviousNode(cDllNode);					
				}			
			}
		}
		return headnode;
	}
}
class DLLNode{
	private int data;
	private DLLNode next;
	private DLLNode previous;
	public DLLNode(int data) {
		this.data=data;
	}
	public void SetData(int data)
	{
		this.data=data;
	}
	public int GetData() {
		return data;
	}
	public void SetDLLNextNode(DLLNode node)
	{
		this.next=node;
	}
	public DLLNode GetDLLNextNode() {
		return next;
	}
	public void SetDLLPreviousNode(DLLNode node)
	{
		this.previous=node;
	}
	public DLLNode GetDLLPreviousNode()
	{
		return previous;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

It&code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值