|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
×
- #include<stdio.h>
- #include<stdlib.h>
- #include<malloc.h>
- #define LEN sizeof(struct node)//定义节点的长度
- #define num 10//定义产生随机数的个数
- typedef int elemtype;//数据元素的类型
- //定义结构体类型节点
- struct node{
- elemtype data;//数据域
- struct node *next;//下一个节点
- };
- //初始化链表 申请内存空间
- struct node *init(){
- struct node *head = (struct node*)malloc (LEN);
- if (head == NULL){
- printf("申请内存失败");
- exit(1);
- }
- head->next=NULL;
- return (head);
- }
- //元素x插入到i的位置
- int Insert(struct node *head,int i, elemtype x){
- //当前访问节点
- struct node *p=head;
- struct node *newp;//新增节点
- int count;//计数器
- if(i<1){
- printf("Argument is error,out of range");//参数范围出错
- return(0);//返回假值表示不成功
- //遍历链表 找到i-1节点
- while(p!=NULL&&count<i-1){
- p=p->next;
- count++;
- }
- if(p==NULL)
- {
- printf("the length of the linked list is less than %d.\n,i-1");
- //需要找到i-1节点 但是链表的长度小于i-1
- return (0);//插入不成功
- }
- //给新节点申请空间
- struct node *newp = (struct node*)malloc (LEN);
- if(newp== NULL){
- printf("申请失败");
- exit(1);}
- //插入新节点 指针指向 数据域插入
- newp->data=x;
- newp->next=p->next;
- p->next=newp;
- return(1);//插入成功;
- }
- //遍历函数
- void Traver(struct node *head){
- struct node *p=head->next;//跳过附加表头的头节点
- while(p!=NULL){
- printf(" %d",p->data);
- p=p->next;
- }
- }
- //创建单链表,其中有若干个随机数
- void Creat(struct node *head){
- int i,j;
- for(i=1;i<=num;i++){
- j=rand();
- Insert(head,i,j);}
- }
- void reverse(){
- struct node *cp=head->next;//当前指针,指向当前正处理的节点
- struct node *pp=NULL;//指向当前节点的前驱
- struct node *np;//指向当前节点的后驱
- while(cp!=NULL){
- np=cp->next;
- cp->next==pp;
- pp=cp;
- cp=np;
- }
- head->next=pp;
-
- }
- /* run this program using the console pauser or add your own getch, system("pause") or input loop */
- void main()
- [color=Red]{[/color] int i=1;//循环控制变量
- struct node *h;//定义头指针
- h=init();//初始化链表
- while(i!=0)
- {
- printf("\n linked list example \n");
- printf("1.creat 10 random number:\n");
- printf("2.reverse the linked list \n");
- printf("3.traver the linked list \n");
- printf("0.exit the program .\n");
- scanf("%d",&i);
- switch(i)
- {
- case 0:exit(0);
- case 1:Creat(h);break;
- case 2:reverse(h);break;
- case 3:Traver(h);break;
- default:printf("input error !");
- }
- }
- [color=Red]}[/color]
复制代码
105 1 E:\数据结构学习\线性链表.c [Error] expected declaration or statement at end of input 提示在main函数括号这里出错
哪位大神帮看一下~谢谢啦 |
|