创建链表并插入数据(有序)
2016-08-28 15:20
495 查看
// // main.m // node // // Created by tk on 16/8/28. // Copyright © 2016年 Company. All rights reserved. // #import <Foundation/Foundation.h> #include <stdio.h> #include <stdlib.h> //定义结构体 struct node { int data; struct node *next; }; /*链表*/ void nodeTest() { struct node *head, *p, *q, *t; int i, n, a; //设置头指针为空 head = NULL; //初试化当前指针 q = NULL; //输入链表的数量 scanf("%d", &n); //输入 for (i = 0; i < n; i++) { scanf("%d", &a); //申请存储空间 p = (struct node *)malloc(sizeof(struct node)); p->data = a; p->next = NULL; if (head == NULL) { head = p; }else { q->next = p; } q = p;//指针q指向当前节点 //至此,一个节点的数据就完成了 } //输出链表 t = head; while (t != NULL) { printf("%d ", t->data); t = t->next;//指向下一个节点 } printf("读入需要插入的数据:"); scanf("%d", &a); t = head; while (t != NULL) { if (t->next == NULL || t->next->data > a) { struct node *d = (struct node *)malloc(sizeof(struct node)); d->data = a; d->next = t->next; t->next = d; break; } t = t->next; } t = head; while (t != NULL) { printf("%d ", t->data); t = t->next; } getchar(); getchar(); return; } int main(int argc, const char * argv[]) { nodeTest(); return 0; }
相关文章推荐
- 如何组织构建多文件 C 语言程序(二)
- 如何写好 C main 函数
- Lua和C语言的交互详解
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言中fchdir()函数和rewinddir()函数的使用详解
- C语言内存对齐实例详解
- C语言编程中统计输入的行数以及单词个数的方法
- C 语言简单加减乘除运算
- C语言自动生成enum值和名字映射代码
- C语言练习题:自由落体的小球简单实例
- 使用C语言判断英文字符大小写的方法
- c语言实现的带通配符匹配算法
- C语言实现顺序表基本操作汇总
- C语言中进制知识汇总
- C语言判断一个数是否是2的幂次方或4的幂次方
- C语言二进制思想以及数据的存储
- 老生常谈C语言动态函数库的制作和使用(推荐)