package com.java.datastructure.lineartable; //线性表 - java-双向链表实现方式 public class DoubLinkList { private Node head; public DoubLinkList() { head = new Node(); head.next = null; head.prior = null; } public void addNode(String data) { Node p = head; //当前只存在多个元素 while (p.next!=null) { p = p.next; } Node temp = new Node(data); p.next = temp; temp.prior = p; } public void delNode(String data) { Node p = head; if(p.next==null) { return ; } while (p.next!=null) { if(p.next.getName().equals(data)) { Node temp = p.next.next; p.next = temp; temp.prior = p.next.prior; break; } else { p = p.next; } } } public void display(String begContetn) { Node p = head; while(p.next!=null) { System.out.println(begContetn+" next Node name :"+p.next.getName()); p = p.next; } while(p.prior!=head) { System.out.println(begContetn+" prior Node name :"+p.getName()); p = p.prior; } System.out.println(p.name); } public String findNode(String data) { Node p = head; while (p.next!=null) { if(p.next.getName().equals(data)) { return data; } else { p = p.next; } } return null; } public void insertBeforeNode(String befNode, String data) { Node p = head; while(p.next!=null) { if(p.next.getName().equals(befNode)) { Node temp = p.next; Node inserData = new Node(data); inserData.next = temp.next; temp.next = inserData; inserData.prior = temp.prior; break; } else { p = p.next; } } } static class Node { private String name; private Node next; private Node prior; public Node() { } public Node(String name) { this.name = name; next = null; prior = null; System.out.println("生产节点:" + name); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Node getNext() { return next; } public Node getPrior() { return prior; } public void setPrior(Node prior) { this.prior = prior; } public void setNext(Node next) { this.next = next; } } public static void main (String[] args) { DoubLinkList list = new DoubLinkList(); list.addNode("hcb1"); list.addNode("hcb2"); list.addNode("hcb3"); list.display("show all"); list.insertBeforeNode("hcb2","hcb2-bef"); list.display("show insert"); list.delNode("hcb2"); list.display("show del"); } }
3. 代码-线性表 - java-双向链表实现方式
最新推荐文章于 2024-02-25 19:03:48 发布