【发布时间】: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->next不是null,因为您没有将其设置为null。删除t3或将t3设置为null不会将t2中的另一个指针设置为null -
当指针指向的对象被销毁时,指针不会自动设置为
0。指针只是保存着内存地址,有没有他不关心的对象,但你得自己去跟踪。 -
你的代码充满了 C 主义。使用 C++。并使用
std::list(或只是std::vector,无论如何这几乎总是更好)。
标签: c++ pointers linked-list singly-linked-list