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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010889390/article/details/52345936
//
//  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;
}


猜你喜欢

转载自blog.csdn.net/u010889390/article/details/52345936
今日推荐