http://www.mitbbs.com//article_t/Programming/31386795.html
发信人: franc (努力 奋斗), 信区: Programming
  标  题: 问个c++删除链表(linked list)节点的问题
  发信站: BBS 未名空间站 (Sat Nov 29 00:09:35 2014, 美东)
  
  在网上看到,基本都是遍历都给定节点,然后将下一个节点指向当前的前一个节点。
  
  大多数的例子,都是对int的链表,所以memory不是问题。如果链表的内容是一个很大
  的数据结构,是否需要释放该节点的内存?如何释放?
  
  请专家指点。
  
  谢谢。
  
  这里是我的一个实现。
  
  "delete cur"试图释放节点内存,似乎多此一举,因为这里cur是个auto变量,函数返
  回时自动释放内存。
  
  void del(Node *&head, int n) {
      Node *cur = head, *pre=NULL;
      while (cur) {
          if (n == cur->val) {
              if (cur == head) {
              /* if the node is the head*/
                  head = head->next;
                  return;
              }
              pre->next = cur->next; //next -> pre
              delete cur; //free the memory. (?)
              return;
          }
          pre = cur;
          cur = cur->next;
      }
  }
  --
  	  
评论
发表评论