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(" ");
}
熱點內容