【问题标题】:how to delete a node in a linked list without accessing its parent node?如何在不访问其父节点的情况下删除链表中的节点?
【发布时间】:2015-11-07 11:33:46
【问题描述】:

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

头=t1
t1->下一个=t2
t2->下一个=t3
t3->下一个=t4

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

我想删除 t3 以便链表只打印 1 2。
但它打印的是 1 2 0 4。

另外,经过检查,我发现 t2->next 不是 NULL,尽管 t3=t2->next 并且我已经删除了 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;
}

【问题讨论】:

  • t2-&gt;next 不是 null,因为您没有将其设置为 null。删除t3或将t3设置为null不会将t2中的另一个指针设置为null
  • 当指针指向的对象被销毁时,指针不会自动设置为0。指针只是保存着内存地址,有没有他不关心的对象,但你得自己去跟踪。
  • 你的代码充满了 C 主义。使用 C++。并使用std::list(或只是std::vector,无论如何这几乎总是更好)。

标签: c++ pointers linked-list singly-linked-list


【解决方案1】:

不访问t2 就无法删除t3,因为您的列表单独链接。

如果你想删除t3 和t4,你应该这样做:

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

如果您只想删除列表中间某处的单个节点(例如t3),您还必须调整 next link from t2:

t2->next=t4;
delete t3;

否则指向被删除的节点。

【讨论】:

  • 你的答案甚至不是他想要的。他想打印1 2 而不是1 2 4
【解决方案2】:

你不能。除非您在其他地方显式存储指向t3 的指针(这有点违背此列表的要点),否则指向t3 的现有指针仅 由t2 持有。因此,要对t3 进行任何操作,您需要访问t2。

编辑:但除了这个小细节,这也许是你想要的。

void deleteNth(node* start, int N)
{
  node* prev = NULL, curr = start;
  while (N-- > 0 && curr != NULL)
  {
    prev = curr;
    curr = curr->next;
  }
  if (curr != NULL && N <= 0)
  {
    prev->next = curr->next;
    delete curr;
  }
}

注意从 1 而不是 0 开始计数 N。

【讨论】:

  • 是的'我建立了一个单链表,它的行为就像一个单链表,请帮忙':((
  • @MartinJames 是的,哈哈。我认为他误解了内存访问的概念 - 或者将列表与向量混淆......
猜你喜欢
  • 2021-05-10
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
相关资源
最近更新 更多