[Java] O(1)时间复杂度删除链表节点Java代码演示 →→→→→进入此内容的聊天室

来自 , 2020-03-04, 写在 Java, 查看 151 次.
URL http://www.code666.cn/view/d005ce7a
  1. package lineartable;
  2. /**
  3.  * 链表节点类
  4.  */
  5. class Node{
  6.     public String value;
  7.     public Node next;
  8.     public Node(String value){
  9.         this.value=value;
  10.         this.next=null;
  11.     }
  12. }
  13. /**
  14.  * 链表类
  15.  */
  16. public class LinkTable {
  17.     public Node head;
  18.     public LinkTable(Node node){
  19.         this.head=node;
  20.     }
  21.     /**
  22.      * 增加节点
  23.      */
  24.     public void addNode(Node node){
  25.         Node end=head;
  26.         while(end.next!=null){
  27.             end=end.next;
  28.         }
  29.         end.next=node;
  30.     }
  31.     /**
  32.      * 删除节点
  33.      * 时间复杂度为O(1)无需遍历链表元素
  34.      */
  35.     public void delNode(Node node){
  36.         node.value=node.next.value;
  37.         node.next=node.next.next;
  38.     }
  39.     /**
  40.      * 打印链表元素
  41.      */
  42.     public void print(){
  43.         Node index=this.head;
  44.         while(index!=null){
  45.             System.out.print(index.value+"-->");
  46.             index=index.next;
  47.         }
  48.         System.out.println("NULL");
  49.     }
  50.    
  51.     public static void main(String [] args){
  52.         LinkTable lt=new LinkTable(new Node("中国"));
  53.         lt.addNode(new Node("美国"));
  54.         Node japanNode=new Node("日本");
  55.         lt.addNode(japanNode);
  56.         lt.addNode(new Node("意大利"));
  57.         lt.addNode(new Node("德国"));
  58.         lt.addNode(new Node("荷兰"));
  59.         lt.print();
  60.        
  61.         lt.delNode(japanNode);
  62.         lt.print();
  63.     }
  64. }
  65.  
  66. /**
  67. 运行结果:
  68. 中国-->美国-->日本-->意大利-->德国-->荷兰-->NULL
  69. 中国-->美国-->意大利-->德国-->荷兰-->NULL
  70. */
  71. //java/6334

回复 "O(1)时间复杂度删除链表节点Java代码演示"

这儿你可以回复上面这条便签

captcha