package alog; import java.awt.*; /** * 双向链表 */ public class DoubleLink { private int size; private Node head; private Node tail; public DoubleLink() { size = 0; head = new Node(-1); tail = new Node(-1); head.next = tail; tail.prev = head; } /** * 节点是否为null */ public boolean isNull(Node node) { return node ==null; } /** * 是否为空 */ public boolean isEmpty() { return size() == 0; } /** * 返回节点个数 * * @return */ public int size() { return size; } /** * 指定索引添加 */ public void insert(int index,int v){ Node node = new Node(v); if(isEmpty()){ node.prev = head; head.next=node; node.next = tail; tail.prev=node; return ; } Node p = head.next; for(int i =1;i<index;i++) p=p.next; node.prev=p.prev; node.next = p; node.prev.next=node; p.prev = node; size++; } /** * 头插法 */ public void addFirst(int data) { Node node = new Node(data); node.next = head.next; node.prev=head; head.next=node; node.next.prev=node; size++; } /** * 删除头节点 */ public int removeFirst() { if (isEmpty()) return -1; Node result = head.next; head.next = result.next; result.next.prev=head; size--; return result.data; } /** * 尾部添加 */ public void addLast(int data) { Node node = new Node(data); node.prev = tail.prev; node.next = tail; tail.prev.next = node; tail.prev = node; size++; } /** * 尾部删除 */ public int removeLast(){ Node result = tail.prev; tail.prev= result.prev; result.prev.next = tail; size--; return result.data; } /** * 打印所有的节点 */ public void show() { Node p = head.next; while (p.data!=-1) { System.out.print(p.data + ","); p = p.next; } } private static class Node { Node prev; Node next; int data; public Node(int data) { prev = null; next = null; this.data = data; } } public static void main(String[] args) { DoubleLink link = new DoubleLink(); link.addLast(10); link.addLast(11); link.addLast(12); link.addLast(13); link.addLast(14); link.addLast(15); link.addLast(16); link.addLast(17); link.addLast(18); link.addLast(19); link.addLast(20); link.removeLast(); link.insert(5,100); link.show(); } }
简单的双向链表
最新推荐文章于 2024-08-14 18:01:26 发布
该博客介绍了如何使用Java实现一个双向链表,包括初始化链表、判断节点是否为空、检查链表是否为空、获取节点数量、在指定位置插入元素、头插法、删除头节点、尾部添加和删除、以及遍历链表显示所有节点的方法。示例代码展示了如何操作这些功能。
摘要由CSDN通过智能技术生成