链接列表删除最后一个节点c ++

时间:2014-04-09 08:49:53

标签: c++ linked-list

我目前正在编写一些代码,它会删除链接列表中的最后一个节点,我的代码如下;但是它将前一个节点删除到最后一个节点;不是最后一个节点本身。

任何帮助将不胜感激:

if(p!=NULL) {
    if( p->next!=NULL) {
        Student *todel = p->next;       
        p->next= p->next->next;
        delete todel; //free(todel);
    } else {
        delete p; //If n = 0 && its the last element, delete it
    }
}

编辑:

我现在编辑的代码如下所示......它不起作用;是因为我指向NULL vaue,然后删除该空值?

if(p!=NULL) {
    if( p->next==NULL) {
            delete p;

  } 
}

3 个答案:

答案 0 :(得分:0)

检查一下。

    if(p!=NULL) {
    if ( p->next!=NULL) {
       while (1) {
        Student *todel = p->next;  
        if (todel->next == NULL) {
          // todel is indeed the last node, delete it
          delete todel;
          p->next = NULL;
          break; // break from infinite while loop that was looking for last node
        }
        else {
           // todel is not last node, go further
           p = todel->next;
        }
     }
  } else {
        delete p; //If n = 0 && its the last element, delete it

  }

}

答案 1 :(得分:0)

在您用于遍历链表的循环中尝试以下操作。

  if(p->next!=NULL) {
        if (p->next->next == NULL) {// Found the second-to-last-node
          delete p->next;  // Kill the last node
          p->next = NULL;  // Make the current node the last node.

      }
  } 

答案 2 :(得分:0)

试试这个,我没有测试过。

void delete_lastnode(Node* head)
{
    Node *p = head;

    if (p == NULL)  // NULL list
        return;

    if (p->next == NULL) // Single node list
    {
        delete head;
        head = NULL;
        return;
    }

    while(p->next->next != NULL) // Find the second-last node
    {
        p = p->next;
    }

    Node* temp = p->next;
    p->next = NULL;
    delete temp;
    temp = NULL;
}