重拾算法Day08-链表

2016-11-09  本文已影响12人  面试小集

链表

本节主要讲链表,包括链表的构造,链表的插入等操作。

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};
int main(int argc, const char * argv[]) {
    struct node *head, *p, *q = NULL, *t;
    int n, a;
    scanf("%d", &n);    //输入个数
    head = NULL;
    for (int i=1; i<=n; i++) {  //输入数据
        scanf("%d", &a);
        p = (struct node *)malloc(sizeof(int));
        p->data = a;
        p->next = NULL;
        
        if (head == NULL) {
            head = p;
        }else {
            q->next = p;
        }
        q=p;
    }
    
    scanf("%d", &a);
    t = head;
    while (t!=NULL) {
        if (t->next == NULL || t->next->data > a) {
            p=(struct node *)malloc(sizeof(struct node));
            p->data = a;
            
            p->next = t->next;  //断裂插入
            t->next = p;
            break;
        }
        
        t=t->next;
    }
    
    t=head;
    while (t!=NULL) {
        printf("%d ", t->data);
        t=t->next;
    }
    
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读