您的位置:首页 > 编程语言

关于链表的新建,删除结点,插入结点的代码

2011-09-24 00:02 330 查看
今天写了一段有关链表的基本操作的程序(C的),放到这大家给批评建议一下哈,,,

#include<stdio.h>
#include<stdlib.h>
struct Link* CreatList();//创建原始链表
struct Link* DelNode(struct Link* head);//删除指定的结点
struct Link* CreatNode(struct Link* head);//在指定位置插入结点
void DispLink(struct Link* head);//打印链表
void FreeList(struct Link* head);//释放单链表

struct Link
{
int data;
struct Link* next;
}

main()
{
//两个整形量记录删除/插入结点的个数
int i=0;
int j=0;
//两个字符用于判断是否需要删除/插入操作
char c,d;
struct Link *head,*p;

head = CreatList();

//打印出原始链表
p = head->next;
while(p!=NULL)
{
printf("%d\t",p->data);
p=p->next;
}
printf("\n");

printf("是否删除数据?(y/n)");
scanf(" %c",&c);
while (c=='y')
{
DelNode(head);
DispLink(head);
printf("是否继续删除数据?");
scanf(" %c",&c);
i++;
}

printf("是否添加数据?(y/n)");
scanf(" %c",&d);
while (d=='y')
{
head = CreatNode(head);
DispLink(head);
printf("是否继续添加新数据?(Y/N)");
scanf(" %c",&d);
j++;
}

printf("%d 个数据被删除\n",i);
printf("%d 个数据被添加\n",j);

FreeList(head);

}
struct Link* CreatList()
{
int dat,i,j=0;//这里用dat代表数据,区别于data,否则会报错
struct Link  *head,*s,*r;//head是头指针,s是新建的结点,r是尾指针

printf("请输入原始链表数据的个数:");
scanf("%d",&i);
head = (struct Link *)malloc(sizeof(struct Link));//分派空间
if(head==NULL)
{
printf("No enough memory to alloc");
exit(0);
}
r = head;
printf("输入原始链表数据:");
while(j<i)
{
s = (struct Link *)malloc(sizeof(struct Link));
if(s==NULL)
{
printf("No enough memory to alloc");
exit(0);
}
scanf("%d",&dat);
s->data = dat;
r->next = s;//将新建结点插入表尾
r = s;//尾指针指向新的表尾
j++;
}
r->next = NULL;

return head;

}
struct Link* DelNode(struct Link* head)
{
int i=0,j,e;
//p是要删除的结点,pr是其前驱
struct Link* p;
struct Link* pr = head;

printf("删除第几个节点的数据?");
scanf("%d",&j);

while(i != (j-1))
{
pr = pr->next;
i++;
}
p = pr->next;//设定p是pr的后继
pr->next = p->next;//将前驱的next指向后继的后继
e = p->data;//e用来存放删除的数据
free(p);//释放空间

return head;
}
struct Link* CreatNode(struct Link* head)
{
int dat;
int i=0,j;
//p是要插入的结点,pr是其前驱
struct Link* p;
struct Link* pr = head;

printf("在第几个节点前插入数据?");
scanf("%d",&j);

p = (struct Link *)malloc(sizeof(struct Link));
if(p==NULL)
{
printf("No enough memory to alloc");
exit(0);
}
if(head == NULL)//如果链表是空表,则直接从第一个结点插入
{
head = p;
}
else
{
while(i != (j-1))
{
pr = pr->next;
i++;
}
}
printf("输入要添加的数据:");
scanf("%d",&dat);
p->data = dat;
p->next = pr->next;//将新建的结点指向其后继
pr->next = p;//将其前驱指向新建结点
return head;
}

void DispLink(struct Link* head)
{
struct Link* p = head->next;

//打印链表
while(p != NULL)
{
printf("%d\t",p->data);
p = p->next;
}
printf("\n");
}
void FreeList(struct Link* head)
{
if (head -> next != NULL)
{
FreeList(head -> next);
}
free(head);
}


以上的代码,放到工程里之后,编译会出现两个waring

D:\My Documents\My file\CB-C\111\main.c|15|warning: return type of 'main' is not 'int'|

D:\My Documents\My file\CB-C\111\main.c|62|warning: control reaches end of non-void function|

单个的C文档编译完全通过,不知为什么到工程里就会有waring呢?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐