建立单链表,删除结点,输出链表
建立有n个结点的单链表,输出链表,然后输入一个整数x,删除所有等于x的结点,删除后再输出链表。要求有(1)创建的函数(2)删除结点的函数(3)输出链表的函数。
输入样例:
6
1 4 2 4 3 4
4
输出样例:
3 2 1
#include <stdio.h>
#include <malloc.h>
struct ming
{
int data;
struct ming* next;
};
struct ming* a;
struct ming* create(struct ming* a, int b[], int n);
void shanchu(struct ming* m);
void printf(struct ming* h);
int main()
{
int b[500];
int n, x;
scanf("%d", &n);
a = (struct ming*)malloc(sizeof(struct ming));
a = create(a, b, n);
shanchu(a);
printf(a);
return 0;
}
struct ming* create(struct ming* a, int b[], int n) //创建新链表并赋值
{
struct ming* c;
a = (struct ming*)malloc(sizeof(struct ming));
a->next = NULL;
for (int i = 0;i < n;i++)
{
c = (struct ming*)malloc(sizeof(struct ming));
scanf("%d", &b[i]);
c->data = b[i];
c->next = a->next; //此处用头插法,可以理解为逆序储存,因此输出也为逆序
a->next = c;
}
return a;
}
void shanchu(struct ming* m) //删除函数
{
struct ming* e, * f;
int x;
scanf("%d", &x);
e = a;
f = e->next; //用两个指针以便同步向后移,确定需要删除的结点的位置
while (f != NULL)
{
if (f->data == x)
{
e->next = f->next;
free(f); //释放f这个结点
f = e->next; //f跳到相邻的下一个,循环继续删除
}
else
{
e = f; //两指针同步后移
f = e->next;
}
}
}
void printf(struct ming* h) // 遍历输出
{
struct ming* d;
d = a->next;
while (d != NULL)
{
printf("%d ", d->data);
d = d->next;
}
}
以下是我的运行结果