第1章第2節練習題2 非遞歸刪除指定結點
阿新 • • 發佈:2017-07-02
ces var con () printf length markdown parent div
問題描寫敘述
在帶頭結點的單鏈表L中。刪除全部值為x的結點,並釋放其空間,假設值為x的結點不唯一,試編寫算法實現以上的操作
算法思想
使用指針p指向數據域為x的結點。使用指針pre指向指針p所指結點的前驅結點,從前向後進行遍歷。假設指針p指向的結點的數據域為x,則刪除。假設指針p指向的結點的數據域不為x,繼續向後遍歷就可以。
算法描寫敘述
void DelNodeX(LNode *head, ElemType x)
{
LNode *pre=head;
LNode *p=head->next;
while(p!=NULL){
if (p->data==x){
pre->next=p->next;
free(p);
p=pre->next;
}else{
pre=p;
p=p->next;
}
}
}
詳細代碼見附件。
附件
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode, *LinkList;
LinkList CreatList(LNode*);
void DelNodeX(LNode*, ElemType);
void Print(LNode*);
int main(int argc,char* argv[])
{
LNode *head;
head=(LNode*)malloc(sizeof(LNode));
head->next=NULL;
head=CreatList(head);
Print(head);
DelNodeX(head,3);
Print(head);
return 0;
}
//頭插法建立單鏈表
LinkList CreatList(LNode *head)
{
LNode *L;
ElemType x;
scanf("%d",&x);
while(x!=999){
L=(LNode*)malloc(sizeof(LNode));
L->data=x;
L->next=head->next;
head->next=L;
scanf("%d",&x);
}
return head;
}
//刪除值為x的結點
void DelNodeX(LNode *head, ElemType x)
{
LNode *pre=head;
LNode *p=head->next;
while(p!=NULL){
if(p->data==x){
pre->next=p->next;
free(p);
p=pre->next;
}else{
pre=p;
p=p->next;
}
}
}
//打印全部結點
void Print(LNode *head)
{
LNode *p=head->next;
while(p){
printf("%4d",p->data);
p=p->next;
}
printf("\n");
}
第1章第2節練習題2 非遞歸刪除指定結點