c语言指针链表

#include <stdio.h>
#include <stdlib.h>
typedef struct note{
    int data;
    struct note* next;//指向下一个结点的地址
}note;
int main()
{
    note *head,*p,*q,*t,*last;
    int n;
    scanf("%d",&n);
    head=NULL;//头指针初始化为空
    for(int i=0;i<n;i++)
    {
        int a;
        scanf("%d",&a);
        getchar();
        p=(note*) malloc(sizeof(note*));//申请一块note结构体类型的地址存放数据和下一个结点的地址
        p->data=a;
        p->next=NULL;//下一个结点指向空
        if(head==NULL)//若当前是第一个结点
            head=p;
        else
            q->next=p;//上一个结点的next指向这个结点
        q=p;
    }
    last=p;//结尾指向p
    t=head;//t指向头指针
    while(t!=NULL)
    {
        printf("%d ",t->data);
        t=t->next;
    }
    printf("\n");
    while(1) {
        int a;
        scanf("%d", &a);
        if(a==-1)
            break;
        t = head;
        int cot = 0;
        if (t->data > a) //若链表中第一个数大于所插入的数,单独处理
        {
            p = (note *) malloc(sizeof(note *));
            p->data = a;
            p->next = t;
            head = p;//头指针指向新的p
            cot = 1;
        } 
        else if (last->data < a) //若链表中最后一个数小于所插入的数,单独处理
        {
            p = (note *) malloc(sizeof(note *));
            p->data = a;
            last->next = p;
            p->next = NULL;
            last = p;//尾指针指向新p
            cot = 1;
        }
        while (t != NULL && cot == 0) {
            if (t->next->data > a) {
                p = (note *) malloc(sizeof(note *));
                p->data = a;
                p->next = t->next;
                t->next = p;
                break;
            } else
                t = t->next;
        }
        t = head;
        while (t != NULL) {
            printf("%d ", t->data);
            t = t->next;
        }
        printf("\n");
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值