如何删除链表中的节点而不访问其父节点?

时间:2015-11-07 11:33:46

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

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

头= t1时
T1->接着= T2
T2->接着= t3时
T3->接着= T4

t1-> data = 1
t2-> data = 2
T3->数据= 3

我想删除t3,以便链表仅打印1个 但相反,它打印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;
}

2 个答案:

答案 0 :(得分:3)

由于您的列表单链接,因此无法在不访问t3的情况下删除t2

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

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

如果您只想删除列表中间某处的单个节点(例如t3),您还必须调整 next 链接< / strong>来自t2

t2->next=t4;
delete t3;

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

答案 1 :(得分:3)

你做不到。除非您在其他地方明确存储指向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;
  }
}

N.B。从1而不是0开始计算N