zoukankan      html  css  js  c++  java
  • 双链表插入 删除详解

    节点结构:

    [cpp] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. struct both_node  
    2. {  
    3.     int key;  
    4.     struct both_node *prev;  
    5.     struct both_node *next;  
    6.     both_node(int k)  
    7.         :key(k),prev(NULL),next(NULL)  
    8.     {}  
    9. };  



    不带头节点的双链表实现插入 删除,

    [cpp] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
      1. 双链表  
      2. //插入  
      3. void insert_both(both_node *&head,int key)  
      4. {  
      5.      if(head==NULL)  
      6.     {  
      7.          head= new both_node(key);  
      8.     } else  
      9.     {  
      10.          both_node *tmp= new both_node(key);  
      11.           if(head->next==NULL)//当插入时链表中只有一个节点的时候  
      12.          {  
      13.              head->next=tmp;  
      14.              tmp->prev=head;  
      15.          } else //链表中已经至少有两个节点  
      16.          {  
      17.              tmp->next=head->next;  
      18.              head->next->prev=tmp;  
      19.   
      20.              head->next=tmp;  
      21.              tmp->prev=head;  
      22.          }  
      23.     }  
      24. }  
      25. //删除  
      26. bool remove_both(both_node *&head,int key)  
      27. {  
      28.      if(head==NULL)  
      29.           return false ;  
      30.      if(head->key==key)//如果是头节点  
      31.     {  
      32.           if(head->next==NULL)//如果只有一个节点  
      33.          {  
      34.               delete head;  
      35.              head=NULL;  
      36.          } else//链表后面还有节点  
      37.          {  
      38.              both_node *tmp=head;  
      39.              head=head->next;  
      40.              head->prev=NULL;  
      41.               delete tmp;  
      42.              tmp=NULL;  
      43.          }  
      44.           return true ;  
      45.     }  
      46.     both_node *cur=head->next;  
      47.      while(cur !=NULL && cur->key !=key)  
      48.          cur=cur->next;  
      49.      if(cur==NULL)//没有找到  
      50.           return false ;  
      51.      if(cur->next !=NULL)//删除的不是尾节点  
      52.     {  
      53.          cur->prev->next=cur->next;  
      54.          cur->next->prev=cur->prev;  
      55.     } else //删除的是尾节点  
      56.     {  
      57.          cur->prev->next=NULL;  
      58.     }  
      59.       
      60.      delete cur;  
      61.     cur=NULL;  
      62.      return true ;  
      63. }
  • 相关阅读:
    javascript js 内存泄露
    javascript js 内存泄露工具使用
    逻辑运算符及按位或与非比较难理解先放着87
    //测试全局变量及局部变量的输出结果的异同
    域名被墙原因
    编写转义字符:78页
    1.1-java创建包和类的方法
    浏览器方法及代码打包成APP的
    一个简单的jsp+servlet实例,实现简单的登录
    LeetCode.985-查询后偶数的总和(Sum of Even Numbers After Queries)
  • 原文地址:https://www.cnblogs.com/Ph-one/p/6367522.html
Copyright © 2011-2022 走看看