脚本宝典收集整理的这篇文章主要介绍了创建链表并插入数据(有序),脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
//
// 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;
}
以上是脚本宝典为你收集整理的创建链表并插入数据(有序)全部内容,希望文章能够帮你解决创建链表并插入数据(有序)所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。