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;
}
}
java实现双向链表
最新推荐文章于 2022-03-21 08:00:00 发布