用c语言编写程序,实现单链表的建立(数据元素为1,2,3,4,5,6),遍历,查找,插入(9,3)和删除

马上答
2024-12-29 12:04:53
推荐回答(1个)
回答1:

void foo(struct node *a)
{
while (a->next != NULL)
{
printf("%d\t", a->val);
a = a->next;
}
printf("\n");
}

// 插入
void insert(struct node *a, struct node *b, int n)
{
int i;
for (i = 1; i < n - 1; i++)
a = a->next;
b->next = a->next;
a->next = b;
}

// 删除
void del(struct node *a)
{
struct node *tmp;
while (a)
{
tmp = a;
a = a->next;
free(tmp);
}
}

int main(void)
{
struct node *a = create();
struct node *b = (struct node*)malloc(sizeof(struct node));
b->val = 9;
foo(a);
insert(a, b, 3);
foo(a);
del(a);
return 0;
}