您的位置:首页 > 其它

删除链表中指定元素

2016-03-06 08:44 239 查看
#include<stdio.h>
#include<stdlib.h>
#define N 5
#define NULL 0
#define OK 1
#define ERROR 0

typedef struct LNode
{
struct LNode *next;
int data;
}LNode,*list;

void creatList(list &l,int n)
{
list p,q;
int i;
l=(list)malloc(sizeof(LNode));
p=l;
for(i=0;i<n;i++)
{
q=(list)malloc(sizeof(LNode));
scanf("%d",&q->data);
p->next=q;
p=q;
}
p->next=NULL;
}

int insertDeleteList(list l,int e)
{
list p,q;
p=l->next;
q=l;
while(p)
{
if(p->data==e)
{
while(q->next!=p)q=q->next;
q->next=p->next;
free(p);
return OK;
}
p=p->next;
}
return ERROR;
}

void printList(list l)
{
list p;
p=l->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
}

int main()
{
list l;
int e;
printf("input a list contain %d elements:\n",N);
creatList(l,N);
printf("input the number you need to delete:\n");
scanf("%d",&e);
if(!insertDeleteList(l,e))
printf("NO\n");
else
printList(l);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: