c语言删除链表
发布时间: 2023-07-30 20:06:53
⑴ 如何删除链表(c语言).
把头节点拆下,把剩下的结点当两个,第一个作为第一个,剩下的作为第二个,先删除第一个,在删除第二个,直到第二个为空
⑵ c语言,删除链表中指定值的节点
删除链表中的一个结点,要把前一个结点和后一个结点连起来,你光删除没有连起来。
Liste
delister
(Liste
liste,
int
v)
{
Liste
tmp1=liste,tmp2=NULL;
int
flag=0;
tmp2=tmp1;
while(
tmp1
!=
NULL
)
{
if(tmp1->valeur
==
v)
{
if(tmp2!=
tmp1)
tmp2->lien=tmp1->lien;
/*头结点可直接删除,中间结点删除前要先连接前后的结点*/
free(tmp1);
tmp1=tmp2->lien;
flag=1;
}
else
{
tmp2=tmp1;
//记录前一个结点
tmp1=tmp2->lien;
}
}
if(!flag)
printf("v
isn't
in
the
list");
return
liste;
}
⑶ C语言如何删除链表头节点
这种删除方法是头节点存放值的,这样可以清楚的看到是否删除掉了头节点。
用p保存头节点 p=head;
head指向下一个节点,成为新的头节点head=p->next;
释放原来的头节点 free(p);
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
voidprintList(structnode*head);
structnode*delHead(structnode*head);
structnode{
intdata;
structnode*next;
};
intmain(){
inti;
structnode*tail,*head,*p;
//尾插法插入数据
p=(structnode*)malloc(sizeof(structnode));
p->data=0;
tail=head=p;
tail->next=NULL;
for(i=1;i<10;i++){
p=(structnode*)malloc(sizeof(structnode));
tail->next=p;
p->data=i;
p->next=NULL;
tail=p;
}
printList(head);
head=delHead(head);
printList(head);
system("pause");
return0;
}
//删除头结点
structnode*delHead(structnode*head){
structnode*p=head;
head=p->next;
free(p);
returnhead;
}
//打印链表
voidprintList(structnode*head){
structnode*p=head;
while(p!=NULL){
printf("%i",p->data);
p=p->next;
}
printf(" ");
}
热点内容