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

//
//  main.m
//  node
//
//  Created by tk on 16/8/28.
//  Copyright © 2016年 Company. All rights reserved.
//

#import 
#include 
#include 

//定义结构体
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;
}

你可能感兴趣的:(创建链表并插入数据(有序))