您的位置:首页 > 编程语言 > C语言/C++

创建链表并插入数据(有序)

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语言