数据结构Java实现:循环链表和双向链表( 二 )


数据结构Java实现:循环链表和双向链表

文章插图
 
如上所示,删除节点必须先找到其前驱节点,在单链表中是不会记录元素的前驱节点的,所以必须从头开始遍历链表,直到找到目标节点的前驱节点,时间复杂度为 O(n) 。
如果是双向链表的结构,每一个节点都会记录其前驱节点,可直接获取,所以此时的时间复杂度为 O(1) 。
数据结构Java实现:循环链表和双向链表

文章插图
 
搞清楚了双向链表的概念,接下来我们用 Java 来实现双向链表的结构 。
 
package com.southwind.link;public class DoubleNode { //数据 public Object data; //下一个节点 public DoubleNode next; //上一个节点 public DoubleNode previous; public DoubleNode(Object data){ this.data = https://www.isolves.com/it/cxkf/yy/JAVA/2019-07-08/data; }}【数据结构Java实现:循环链表和双向链表】package com.southwind.link;public class DoubleLinkedList { public int size; public DoubleNode head; /** * 添加元素 * @param obj * @return */ public DoubleNode add(Object obj){ DoubleNode newNode = new DoubleNode(obj); if(size == 0){ head = newNode; }else{ DoubleNode target = head; while(target.next!=null){ target = target.next; } target.next = newNode; newNode.previous = target; } size++; return newNode; } /** * 在指定位置插入元素 * @return */ public DoubleNode insert(int index,Object obj){ if(index >= size){ return null; } DoubleNode newNode = new DoubleNode(obj); if(index == 0){ newNode.next = head; head.previous = newNode; head = newNode; }else{ DoubleNode target = head; int pos = 0; while(pos != index){ target = target.next; pos++; } newNode.previous = target.previous; newNode.previous.next = newNode; newNode.next = target; } size++; return newNode; } /** * 删除链表头部元素 * @return */ public DoubleNode removeHead(){ if(size > 0){ DoubleNode node = head; head = head.next; size--; return node; }else{ return null; } } /** * 删除指定位置元素 * @return */ public DoubleNode remove(int index){ if(index >= size){ return null; } DoubleNode result = head; if(index == 0){ DoubleNode node = head; head = head.next; }else{ DoubleNode target = head; int pos = 0; while(pos != index){ target = target.next; pos++; } target.previous.next = target.next; } size--; return result; } /** * 删除指定元素 * @return */ public DoubleNode removeNode(Object obj){ DoubleNode target = head; if(obj.equals(target.data)){ DoubleNode node = head; head = head.next; size--; }else{ while(target.next!=null){ if(obj.equals(target.data)){ target.previous.next = target.next; size--; break; } target = target.next; } } return target; } /** * 返回指定元素 * @return */ public DoubleNode findNode(Object obj){ DoubleNode target = head; while(target.next!=null){ if(obj.equals(target.data)){ return target; }else{ target = target.next; } } if(target.next==null && obj.equals(target.data)){ return target; } return null; } /** * 输出链表元素 */ public void show(){ if(size > 0){ DoubleNode node = head; int length = size; System.out.print("["); while(length > 0){ if(length == 1){ System.out.print(node.data); }else{ System.out.print(node.data+","); } node = node.next; length--; } System.out.println("]"); }else{ System.out.println("[]"); } }}



推荐阅读