1. 程式人生 > >按值查詢連結串列以及後插入

按值查詢連結串列以及後插入

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

typedef struct student
{
    int num;
    struct student *next;
}Lstudent,*LPstudent;

void InitLink(LPstudent *phead)
{
    Lstudent *ptr,*r;
    *phead=NULL;
    //-----------------------------------------------
    ptr=malloc(sizeof(Lstudent));
    *phead=ptr;
    ptr->next=NULL;
    //------------------------------------------------
    int n;
    printf("please input number of student:\n");
    scanf("%d",&n);
    while(n>0)
    {
        ptr=malloc(sizeof(Lstudent));
        ptr->num=n;
        ptr->next=NULL;
        if((*phead)->next==NULL)///////////////////////////////
            (*phead)->next=ptr;//////////////////////////////////
        else
            r->next=ptr;

        r=ptr;

        printf("please input number of student:\n");
        scanf("%d",&n);

    }
}

void printf_link(Lstudent *ptri)
{
    ptri=ptri->next;/////////////////////////////////////////////////
    while(ptri!=NULL)
    {
        printf("%d   ",ptri->num);
        ptri=ptri->next;
    }
}

LPstudent LocateElem(LPstudent ptr,int i)//查詢函式
{
    ptr=ptr->next;
    if(ptr->num==i)return ptr;
    else{
        while(ptr->next!=NULL)
        {
            ptr=ptr->next;
            if(ptr->num==i)return ptr;
        }}
    return NULL;
}

void ListInsert(LPstudent ptr,int i,int j)//插入函式
{
    LPstudent p1=LocateElem(ptr,i);
    if(p1==NULL)
        printf("no %d student\n",i);

    else
    {LPstudent p2=malloc(sizeof(Lstudent));
        p2->num=j;
        p2->next=p1->next;
        p1->next=p2;
        printf("--------after insert------------\n");
        printf_link(ptr);
    }

}
int main()
{
    LPstudent head;
    InitLink(&head);
    printf_link(head);

    LPstudent ptr=LocateElem(head,10);
    if(ptr!=NULL)
        printf("this is:%d\n",ptr->num);
    else
        printf("NULL\n");

    ListInsert(head,10,11);

}