C语言-数据结构-插入

来源:互联网 发布:2016淘宝好评返现违规 编辑:程序博客网 时间:2024/06/06 12:52
#include <stdio.h>
#include <stdlib.h>
struct node{
    int date;
    struct node *next;
};
struct node* creattable(int n)///n节点个数
{
    int i,a;
    struct node *head,*p1,*p2;
    head = NULL;  ///头结点为空
    ///输入节点内容
    for(i=n;i>0;i--)
    {
        ///(类型*)malloc(大小),返回指针
        ///sizeof(结构体名)计算结构体大小
        p1=(struct node*)malloc(sizeof (struct node));//申请内存空间
        ///a用来保存节点的date
        scanf("%d",&a);
        p1->date = a;
        if(head==NULL)
        {
            head=p1;
            p2=p1;
        }
        else
        {
            p2->next = p1;
            p2 = p1;
        }
    }
    p2->next = NULL;
    ///返回头结点
    return head;
}
void insert(struct node *head)
{
    char ch;
    int iposx,numi,j=0,k=0;
    struct node *q,*s;
    q=head;
    do
    {
    printf("Please enter index:");
    scanf("%d",&iposx);
    printf("Please enter number:");
    scanf("%d",&numi);
    while(q&&j<iposx-1)
    {
        q=q->next;
        ++j;
    }
    if(!q||j>iposx-1)
    {
        exit(1);
    }
      s=(struct node*)malloc(sizeof (struct node));
      s->date=numi;
      s->next=q->next;
      q->next=s;
    printf("\n是否需要输入更多序列 (Y/N) ? ");
    getchar();
    ch=getchar();
    k++;
    }
    while(ch=='y'||ch=='Y');
}
int main()
{
    int n;
    struct node *p;
    printf("Please enter the number of nodes:");
    scanf("%d",&n);//节点个数
    p=creattable(n);
    insert(p);
    while(p)
    {
        printf("%d ",p->date);
        p = p->next;
    }
    return 0;
}
原创粉丝点击