簡體   English   中英

鏈表刪除最后一個節點C ++

[英]Linked list deleting last node c++

我目前正在編寫一些代碼,該代碼將從鏈表中刪除最后一個節點,下面是我的代碼; 但是它將前一個節點刪除到最后一個節點; 不是最后一個節點本身。

任何幫助將不勝感激:

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值,然后刪除該Null值?

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

  } 
}

檢查這個。

    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

  }

}

在遍歷鏈表的循環內嘗試以下方法。

  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.

      }
  } 

試試這個,我沒有測試。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM