Be_envious 发表于 2011-8-13 03:10:56

单链表创建,输出,插入算法源码__有不足处希望大家帮我改正.

本帖最后由 Be_envious 于 2011-8-13 03:14 编辑

#include<stdio.h>
#include<malloc.h>

struct node
{
int data; //数据域
struct node * next; //指针域
};

//声明函数
struct node * creat(void);
void print(struct node *);
struct node * insert(struct node *);

//主函数
int main(void)
{
struct node * phead = NULL;

phead=creat();
print(phead);
insert(phead);
return 0;
}

struct node * creat(void)
{
int len; //要输入结点的个数
int i;
int var; //用于存放用户输入的零时数据

//分配一个没有任何数据的头结点
struct node * phead = (struct node *)malloc(sizeof(struct node));

if(NULL == phead)
{
printf("内存分配失败,程序自动退出");
exit(-1);
}

struct node * tail=phead;
tail->next=NULL;

printf("输入结点的个数: ");
scanf("%d",&len);

for(i=0;i<len;i++)
{
printf("输入第%d个节点的数据: ",i+1);
scanf("%d",&var);

struct node * pnew = (struct node *)malloc(sizeof(struct node));
if(NULL == pnew)
{
printf("内存分配失败,程序自动退出");
exit(-1);
}
pnew->data = var;
tail->next = pnew;
pnew->next = NULL;
tail=pnew;
}
return (phead);
}

void print(struct node *phead)
{
struct node * p = phead->next;

while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}


struct node * insert(struct node *phead)
{
int flag; //标志
do
{
int n; //需要在第几个元素前插入数据
int i=0;
int ins; //要插入的数据

printf("输入要在第几个元素后插入数据:");
scanf("%d",&n);

struct node * p = phead->next;
while( p && i<n-1 )
{
p=p->next;
++i;
}

struct node * insert_data = (struct node *)malloc(sizeof(struct node));
if(NULL == insert_data)
{
printf("内存分配失败系统,系统自动退出");
exit(-1);
}

printf("输入要插入的数据:");
scanf("%d",&ins);
/*if(n == 0) //当在头指针后插入时会出现问题 写下这段代码,会使在第一个数据上发生替换
{
insert_data->data=ins;
insert_data->next=phead->next;
phead->next=insert_data;
}*/
insert_data->data=ins;
insert_data->next=p->next;
p->next=insert_data;
print(phead);
printf("输入0退出,输入其他值继续插入: ");
scanf("%d",&flag);

}
while(flag);
return (phead);
}

cqk2980 发表于 2013-5-17 13:52:01

无回帖,不论坛,这才是人道。

我挖 发表于 2013-7-2 21:28:25

看帖,回复支持下

bafengao 发表于 2013-7-2 22:10:14

支持楼主 好好学习

我挖 发表于 2013-7-3 17:57:17

看帖,支持下

Cocol 发表于 2013-7-3 19:34:24

看看,回复支持下

Cocol 发表于 2013-7-4 20:49:44

再看看,支持下

arise 发表于 2013-12-27 17:22:48

感谢楼主无私奉献!

瑞恩 发表于 2014-1-12 07:02:38

学习啦,链表研究一下
页: [1]
查看完整版本: 单链表创建,输出,插入算法源码__有不足处希望大家帮我改正.