C语言高手救命呀~~~

发布网友 发布时间:9分钟前

我来回答

1个回答

热心网友 时间:10分钟前

/****************************************************

实现单向链表(创建,打印,删除,添加)
lianbiao.c

****************************************************/
#include "stdio.h"
typedef struct LianBiao
{
int date;
struct LianBiao *next;
}LianBiao;

int sum; //全局变量num记录节点的个数
LianBiao* LineBiaoCreate()
{
struct LianBiao *p1 = NULL;
struct LianBiao *p2 = NULL;
struct LianBiao *head;
sum = 0;
p1 =(struct LianBiao *)malloc(sizeof(struct LianBiao));
if (p1 == NULL)
{
printf("error");
return NULL;
}
else
{
printf("please input lianbiao number:\n");
scanf("%d",&(p1->date));
}
p2 = p1;
while (p1->date != 0)
{
sum++;
if (sum == 1)
{
head = p1;
p2->next = NULL;
}
else
{
p2->next = p1;
}
p2 = p1;
p1 =(struct LianBiao *)malloc(sizeof(struct LianBiao));
printf("please input lianbiao number:\n");
scanf("%d",&(p1->date));
}
p2->next = NULL;
free(p1);
p1 = NULL;
return head;
}

void PrintLineBiao(struct LianBiao *head)
{
struct LianBiao *p1;
struct LianBiao *p2;
p1 = head;
printf("链表数据:%d个\n",sum);
while (p1 != NULL)
{
printf("%d\n",p1->date);
p1 = p1->next;
}
}

struct LianBiao* DelLianBiao(struct LianBiao * head, int num)
{
struct LianBiao *p1;
struct LianBiao *p2;
if (head == NULL)
{
printf("this lianbiao is NULL");
return NULL;
}
p1 = head;
while(p1->date != num && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if (num == p1->date)
{
if (p1 == head)
{
head = p1->next;
}
else
{
p2->next = p1->next;
}
sum = sum - 1;
}
else
{
printf("not find this number!");
}
return head;
}
InsertLianBiao(struct LianBiao* head, int num)
{
int i = 1;
struct LianBiao *p1,*p2;
p1 = head;
if (num > sum && num < 0)
{
printf("insert error!");
}
while (i < sum-1)
{
p1 = p1->next;
i++;
}
p2 = (struct LianBiao*)malloc(sizeof(struct LianBiao));
printf("please input Insert lianbiao number\n");
scanf("%d",&(p2->date));
p2->next = p1->next;
p1->next = p2;
sum++;
}
void main()
{
int i;
struct LianBiao * head;
head = LineBiaoCreate();
PrintLineBiao(head);
printf("输入要删除的数:\n");
scanf("%d",&i);
head=DelLianBiao(head,i);
PrintLineBiao(head);
printf("输入要插入的位置:\n");
scanf("%d",&i);
InsertLianBiao(head,i);
PrintLineBiao(head);
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com