2018.5.19(链表)c语言版

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

struct List
{
    int data;
    List *next;
};

List *Create_01()//按输入顺序建立链表;
{
    List *head=NULL,*tail=NULL,*p;
    int number;

    printf("Input some number for this list until the number is zero!\n");
    while(cin>>number)
    {
        if(number==0)
            break;
        p=(List*)malloc(sizeof(List));
        p->data=number;
        p->next=NULL;

        if(head==NULL)
            head=p;
        else
            tail->next=p;
        tail=p;
    }
    return head;
}

List *Create_02()//向头节点插入数据;
{
    List *head=NULL,*p=NULL;
    int number;

    printf("Input some number for this list until the number is zero!\n");
    while(cin>>number)
    {
        if(number==0)
            break;
        p=(List*)malloc(sizeof(List));
        p->data=number;
        if(head==NULL)
        {
             head=p;
             head->next=NULL;
        }
        else
            p->next=head;
        head=p;
    }
    return head;
}

List *Insert(List *head,int x,int i)//在i位置插入数据x;
{
    List *p=head;
    List *new_p;
    new_p=(List*)malloc(sizeof(List));

    int j=1;
    new_p->data=x;

    if(i==1)
    {
        new_p->next=head;
        head=new_p;
    }
    else
    {
        while(j<i-1&&p->next!=NULL)
        {
            p=p->next;
            j++;
        }
        if(j==i-1)
        {
            new_p->next=p->next;
            p->next=new_p;
        }
        else
            printf("Insert is failure!\n");
    }
    return head;
}

void print(List *head)//打印链表
{
    for(List *p=head;p!=NULL;p=p->next)
        printf("%d ",p->data);
    printf("\n");
}

int main()
{
    List *head_01;
    head_01=Create_01();
    print(head_01);

    printf("Input the number's data and is position until the data and position are zero!\n");
    int position,data;
    while(cin>>data>>position)
    {
        if(data==0&&position==0)
            break;

        head_01=Insert(head_01,data,position);

        print(head_01);
    }


    List *head_02;
    head_02=Create_02();
    print(head_02);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/violet_ljp/article/details/80375953