建立长度为n的单链表,n>0,删除单链表中等于给定值的元素。数据类型指定为整型。
c语言作业题,这里学的不太清楚,请各位家人指点指点~
建立长度为n的单链表,n>0,删除单链表中等于给定值的元素。数据类型指定为整型。
c语言作业题,这里学的不太清楚,请各位家人指点指点~
供参考:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct lnode {
int data;
struct lnode* next;
}lnode, * linklist;
void buildlist(linklist* L, int n)
{
int i;
(*L) = (linklist)malloc(sizeof(lnode));
(*L)->next = NULL;
lnode* s, * r = (*L);
for (i = 0; i < n; i++)
{
s = (lnode*)malloc(sizeof(lnode));
s->next = NULL;
s->data = rand() % 100 + 1;
r->next = s;
r = s;
}
}
void disp(linklist L)
{
lnode* s = L->next;
while (s)
{
printf(s == L->next ? "%d" : "->%d", s->data);
s = s->next;
}
printf("\n");
}
void deletex(linklist L, int x)
{
int flg = 0;
lnode* p = L->next, * r = L;
while (p)
{
if (p->data != x){
r = p;
p = p->next;
}
else{
r->next = p->next;
free(p);
p = r;
flg = 1;
}
}
if (!flg)
printf("Not Found.\n");
}
int main()
{
int i, n;
linklist L = NULL;
srand((unsigned int)time(NULL));
printf("Input len:");
scanf("%d", &n);
buildlist(&L, n); //建立长度为n的单链表
disp(L);
printf("Delete num:");
scanf("%d", &n);
deletex(L, n); //删除单链表中等于给定值的元素
disp(L);
return 0;
}