一 链表中存的int数据
#include<stdio.h>
#include<stdlib.h>
struct MyStruct
{
int data;
struct MyStruct * next;
};
void chuangjian_and_charu(struct MyStruct* head,struct MyStruct*a)//头插法,将新的节点插在头结点之后。
{
int n;
scanf_s("%d", &n);
for (int i = 0; i < n; i++)
{
struct MyStruct* s = (struct MyStruct*)malloc(sizeof(struct MyStruct));
scanf_s("%d", &s->data);
s->next = head->next;
head->next = s;
}
while (a->next != NULL)//如果a的下一个结点不为NULL,也就是说如果a结点后还有节点存在,那就输出a后面结点中保存的数据。
{
printf("%d ", a->next->data);
a = a->next;//a结点后移
}
}
void delete_(struct MyStruct* head, struct MyStruct* a)
{
a = head;
struct MyStruct* b=head;创建b节点
int m;
int i = 0;
printf("输入你要删除第几个节点:\n");
scanf_s("%d", &m);
while (b->next!=NULL)
{
i++;
a = b;
b = b->next;
if (i==m)
{
a->next = b->next;
free(b);//与malloc相对应,free释放内存
b = a->next;
}
printf("%d ", b->data);
}
}
int main()
{
struct MyStruct* head = (struct MyStruct*)malloc(sizeof(struct MyStruct));//创建头节点,并分配内存
head->next = NULL;//head指针的初始化
struct MyStruct* a;
a = head;//让指针a指向head
chuangjian_and_charu(head,a);//调用chaungjian_and_charu
delete_(head,a);//调用delete_
}