|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 ck329054222 于 2013-8-26 18:10 编辑
- #include<stdio.h>
- #include<malloc.h>
- #include<stdlib.h>
- #define LEN sizeof(struct student)
- struct student
- {
- int num;
- struct student *next;
- };
- struct student *creat(); //创建链表
- struct student *del(struct student *head,int m);//插入链表操作
- void print(struct student *head);//将链表打印输出
- int n; //全局变量 ,记录链表总共有多少数据
- int main(void)
- {
- struct student *stu,*p;
- int m;
- stu = creat();
- p = stu;
- print(p);
-
- printf("\n请输入你要删除的学号:");
-
- scanf("%d",&m);
- print(del(p,m));
-
-
- return 0;//exit(0)
- }
- struct student *creat()
- {
- struct student *head;//创建头节点
- struct student *p1,*p2;
- //p1负责创建新节点,p2负责存储节点,每循环一次,指针递增一次(分配了新的内存空间)
-
- p1=p2=(struct student *)malloc(LEN);
-
- printf("请输入学号:");
- scanf("%d",&p1->num);
-
- head = NULL;//
- n = 0;
- while(p1->num)
- {
- n++;//链表节点个数
- if(n == 1)
- {
- head = p1;
- }//表示链表只有一个结点
- else
- {
- p2->next = p1;//此处p1为下面创建的新结点
- }
- p2 = p1;//将新结点保存
- p1=(struct student *)malloc(LEN);//创建下一个结点
- printf("请输入学号:");
- scanf("%d",&p1->num);
- }
-
- p2->next = NULL;//链表结束,丢弃p1,p2为最后一个节点
-
- return head;
- }
- void print(struct student *head)
- {
- struct student *p;
- printf("\n总共有%d个学生\n",n);
-
- p=head;
- if(head) //判断头是否为空指针
- {
- while(p) //判断至最后一个结点为空
- {
- printf("学号:%d\n",p->num);
- p = p->next; //下次循环指向下一个节点
- }
- }
- }
- struct student *del(struct student *head,int m)
- {
- struct student *p1,*p2;
- p1 = head;
- if(head)
- {
- while( p1->num != m)
- {
- p2 = p1;
- p1 = p1->next;
- }
- if(p1 == NULL)
- printf("没有找到结点\n");
- else
- {
- if(p1 == head)
- head = p1->next;
- else
- p2->next = p1->next;
- }
- n = n-1;
- }
- return head;
- }
-
-
- 是编码问题。将UTF-8改为ANSI就可以了
复制代码 |
|