package com.itcast.datastructure.linkedlist; //测试类 public class DoubleLinkedList { public static void main(String[] args) { DNode a=new DNode(1,"a"); DNode b=new DNode(2,"b"); DNode c=new DNode(3,"c"); DNode d=new DNode(4,"d"); DoubleLinkedListDemo lld=new DoubleLinkedListDemo(); lld.addById(c); lld.addById(d); lld.addById(b); lld.addById(d); lld.showNodes(); lld.update(new DNode(3,"cc")); lld.showNodes(); lld.delete(3); lld.showNodes(); } } //双向链表 class DoubleLinkedListDemo { private DNode head = new DNode(0, ""); //链表末尾添加 public void addEnd(DNode node) { DNode temp = head; while (true) { if (temp.next == null) { break; } temp = temp.next; } temp.next = node; node.pre = temp; } //按照id顺序添加 public void addById(DNode node){ DNode temp=head; while (true){ if(temp.next==null){ temp.next=node; node.pre=temp; break; } if (temp.next.id>node.id){ temp.next.pre=node; node.next=temp.next; temp.next=node; node.pre=temp; break; } if(temp.next.id==node.id){ System.out.printf("编号%d已经存在\r\n", node.id); return; } temp=temp.next; } } //修改节点 public void update(DNode newNode){ DNode temp=head.next; while(true){ if(temp==null){ System.out.printf("%d 不存在\r\n",newNode.id); return; } if(temp.id==newNode.id){ temp.name=newNode.name; return; } temp=temp.next; } } //删除节点 public void delete(int id){ DNode temp=head.next; while (true){ if(temp==null){ System.out.printf("%d 不存在\r\n",id); return; } if (temp.id==id){ temp.pre.next=temp.next; if (temp.next!=null) temp.next.pre=temp.pre; return; } temp=temp.next; } } //展示链表数据 public void showNodes(){ DNode temp=head.next; while (true){ if(temp==null) break; System.out.println(temp); temp=temp.next; } } } //节点类 class DNode{ public int id; public String name; public DNode next; public DNode pre; public DNode(int id,String name){ this.id=id; this.name=name; } @Override public String toString() { return "Node{" + "id=" + id + ", name='" + name + '\'' + '}'; } }