C++ 删除链表中的某一节点
首先定义链表的结构:
struct ListNode {
int val; //存储数据
ListNode *next; //next指针
ListNode() : val(0), next(NULL) {} //类似构造函数
ListNode(int x) : val(x), next(NULL) {}
};
循环创建链表:
int main()
{
//创建链表
ListNode *head = new ListNode(); //头节点
ListNode *p=head; //指针
int i=1;
while(i<5){
ListNode *node = new ListNode(i); // 初始化一个节点
p->next = node;
p=p->next;
i++;
}
p->next=NULL;//最后一个节点的指针指向空
p=head;
cout<<"删除前:";
while(p){
cout<<p->val<<" ";
p=p->next;
}
cout<<endl;
p=head;
//假设删除值为2的节点
while(p->next){
if(p->next->val==2){
ListNode *tem=p->next;
p->next=p->next->next;
delete tem;
}
p=p->next;
}
p=head;
cout<<"删除后:";
while(p){
cout<<p->val<<" ";
p=p->next;
}
return 0;
}
输出以下链表中内容:
删除前:0 1 2 3 4
删除后:0 1 3 4