簡體   English   中英

如何解決此細分錯誤?

[英]How to fix this segmentation error?

引起錯誤的行在旁邊注釋,我試圖從鏈接列表中刪除一個節點,然后在要刪除的節點旁邊設置“ previous->”旁邊時發生分段錯誤。

void LinkedList::removeNode(int k)
{
    Node* pre = NULL; 
    Node* curr = NULL;
    Node* temp = NULL;

    pre = head;

    curr = head->get_next();

    for(int i =1; i<=length; i++)
    {

        if (i == k)
        {
            temp = curr->get_next();
            pre->set_next(temp); // this line causes segmentation error
            if(curr == tail)
            {
                tail = pre;
            }
            delete curr;
            break;
        }
        pre = curr;
        if(curr->get_next() != NULL)
        {
            temp = curr->get_next();
            curr = temp;
        }
    }

看起來像您遍歷鏈表,但具有一些神秘的length迭代限制,在節點刪除代碼中未對此進行修改...

下面是一些優化的代碼:

void LinkedList::removeNode(int k)
{

    if (head == NULL)
        return;

    Node* curr = head; 
    Node* next = NULL;

    int i = 0;
    while ((next = curr->get_next()) != NULL) {
        if (++i == k) {
            curr->set_next(next->get_next());

            if (next == tail)
                tail = curr;

            next->set_next(NULL);
            delete next;
            length--;
            break;
        }

        curr = next;
    }
}

暫無
暫無

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

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