我创建了一个4个节点t1 t2 t3 t4的链表(按顺序),
这样

头= t1
t1-> next = t2
t2-> next = t3
t3-> next = t4

t1->数据= 1
t2->数据= 2
t3->数据= 3

我想删除t3,以便链接列表仅打印1 2。
而是打印1 2 0 4。

另外,在检查之后,我发现尽管t3 = t2-> next的事实使t2-> next不为NULL,并且我已经删除了t3。

因此,如何在不访问t2的情况下删除t3?

#include<bits/stdc++.h>
using namespace std;

typedef struct linkedList
{
    int data;
    linkedList *next;
}node;

node* getNewNode()
{
    node* nw=new node;
    nw->next=NULL;
    return nw;
}

void display(node* &start)
{
    if(!start) return ;
    node *temp=start;
    while(temp)
    {
        cout<<temp->data<<" ";
        temp=temp->next;
    }
    cout<<endl;
}

int main()
{
    //create a linked list
    node *head;
    node*t1,*t2,*t3,*t4;
    t1=new node;
    t2=new node;
    t3=new node;
    t4=new node;

    t1->data=1;
    t2->data=2;
    t3->data=3;
    t4->data=4;

    head=t1;
    t1->next=t2;
    t2->next=t3;
    t3->next=t4;

    //the linked list is 1 2 3 4
    cout<<"the original linked list is ";
    display(head);

    //now, delete t3
    delete t3;
    t3=NULL;

    //here, it is desired that the linked list prints 1 2
    //but the linked list prints 1 2 0 4
    cout<<"the linked list after deleting t3 is ";
    display(head);

    //I don't understand why t2->next is not null
    //despite the fact that t2->next=t3
    //and I have deleted t3
    if(t2->next) cout<<endl<<"t2->next is not null"<<endl;

   return 0;
}

最佳答案

由于您的列表是单链接的,因此无法删除t3而不访问t2

如果要删除t3t4,则应执行以下操作:

t2->next=NULL;
delete t3;
delete t4;


如果您只想删除列表中间某个地方的单个节点(例如t3),则还必须从next调整t2链接:

t2->next=t4;
delete t3;


否则,它指向已删除的节点。

关于c++ - 如何在不访问父节点的情况下删除链表中的节点?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33582271/

10-12 07:35