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

来源:互联网 发布:淘宝子账号在哪关闭 编辑:程序博客网 时间:2024/05/21 07:55
////  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;}
0 0
原创粉丝点击