Java数据结构|【浅学Java数据结构】简单模拟实现双向链表

【Java数据结构|【浅学Java数据结构】简单模拟实现双向链表】模拟实现:

public class DoubleLinkedList { static class ListNode{ int data; ListNode next; ListNode prev; public ListNode(int val){ this.data=https://www.it610.com/article/val; this.next=null; this.prev=null; } }public ListNode head; //标记头 public ListNode last; //标记尾//遍历打印链表 public void display(){ ListNode cur=this.head; while(cur!=null){ System.out.print(cur.data+" "); cur=cur.next; } System.out.println(); }//尾插法 public void addLast(int val){ ListNode node=new ListNode(val); if(this.head==null) { this.head = node; this.last = node; }else{ this.last.next=node; node.prev=this.last; this.last=node; } }//头插法 public void addFirst(int val){ ListNode node=new ListNode(val); if(this.head==null) { this.head = node; this.last = node; }else{ node.next=this.head; this.head.prev=node; this.head=node; } }//任意位置插入,第一个数据节点为0号下标 public void addIndex(int index,int val){ ListNode node=new ListNode(val); ListNode cur=this.head; int count=0; while(cur!=null){ cur=cur.next; count++; } if(index<0||index>count){ throw new RuntimeException("下标不合理"); } if(index==0){ addFirst(val); return; } if(index==count){ addLast(val); return; }cur=this.head; for(int i=0; i

测试代码:
public class Test { public static void main(String[] args) { DoubleLinkedList linkedList = new DoubleLinkedList(); linkedList.addLast(1); linkedList.addLast(1); linkedList.addLast(1); linkedList.addLast(2); linkedList.addLast(3); linkedList.addLast(4); linkedList.addLast(5); linkedList.display(); linkedList.addIndex(0,10); linkedList.display(); linkedList.addIndex(8,20); linkedList.display(); linkedList.addIndex(4,30); linkedList.display(); boolean flg=linkedList.contains(10); System.out.println(flg); linkedList.remove(10); linkedList.display(); linkedList.remove(20); linkedList.display(); linkedList.remove(30); linkedList.display(); linkedList.removeAll(1); linkedList.display(); int len=linkedList.size(); System.out.println(len); linkedList.clear(); } }

运行结果:

    推荐阅读