本文主要是介绍Java实现 双链表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
双链表较之单链表多了前趋和后继,但是tail.next都为null
节点类:
public class DNode {String name;DNode prev;DNode next;public DNode(String name, DNode prev, DNode next) {this.name = name;this.prev = prev;this.next = next;}public DNode(String name) {this.name = name;this.prev = null;this.next = null;}public DNode() {this.prev = null;this.next = null;}
}
链表类:
public class DLink {public DNode head;public DLink() {this.head = new DNode();}public void addNode(String name) {DNode d = head;while (d.next != null) {d = d.next;}d.next = new DNode(name, d, null);}/*** 删除某节点* @param name*/public void delNode(String name) {DNode d = head;//遍历while (d.next != null) {if(d.next.name.equals(name)) {//更改将要删除节点后一节点的前趋为currentd.next.next.prev = d.next.prev;d.next = d.next.next;break;}else {d = d.next;}}}/*** data 前插入节点* @param data* @param name* @return*/public boolean insertNode(String data,String name) {DNode d = head;DNode insertNode = new DNode(name, null, null);while (d.next != null) {if(d.next.name.equals(data)) {/*** 设置插入节点的前趋和后继(d.next 为当前节点data)*/insertNode.next = d.next;insertNode.prev = d.next.prev;/*** 设置当前节点的前趋*/d.next.prev = insertNode;/*** 设置当前节点*/d.next = insertNode;return true;}else {d = d.next;}}return false;}/*** 替换某节点的值* @param data* @param name* @return*/public boolean setValue(String data,String name) {DNode d = head;while (d.next != null) {d = d.next;if(d.name.equals(data)) {d.name = name;return true;}}return false;}/*** 遍历*/public void display() {DNode d = head;while (d.next != null) {d = d.next;System.out.println(d.name);}}}
测试代码:
DLink dLink = new DLink();dLink.addNode("1");dLink.addNode("2");dLink.addNode("3");dLink.addNode("4");dLink.display();System.out.println("-------------------------");dLink.setValue("3","5");dLink.display();
这篇关于Java实现 双链表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!