2013/07/27

資料結構 單向鍊結串列插入


#include <stdio.h>
#include <stdlib.h>
 
#define MAX 10
 
struct List
{
    int num;
    int total;
    struct List *Next;
};
typedef struct List Node;
typedef Node *Link;
 
int Data[2][MAX]={1,3,5,7,9,2,4,6,8,10,
                    141,77,150,200,19,12,1414,176,188,20};
 
 
Link Insert_List(Link Head, Link New, int key)
{
    Link Pointer = Head;

    while(1){

        if(Pointer == NULL){
            New->Next = Head;
            Head = New;
            break;
        }

        if(Pointer->num == key){
            New->Next = Pointer->Next;
            Pointer->Next = New;
            break;
        }

        Pointer = Pointer->Next;
    }

    return Head;
}


void Print_List(Link Head)
{
    Link Pointer = Head;

    while (Pointer != NULL){
        printf("[%d, %d] ", Pointer->num, Pointer->total);
        Pointer = Pointer->Next;
    }
    printf("\n");
}
 
void Free_List(Link Head)
{
    Link Pointer;
    while(Head != NULL){
        Pointer = Head;
        Head = Head->Next;
        free(Pointer);
    }
}
 
Link Create_List(Link Head)
{
    Link New;
    Link Pointer;
    int i;
 
    Head = (Link)malloc(sizeof(Node));
     
    if(Head == NULL)
        printf("Memory allocate Failure!!\n");
    else{
        Head->num = Data[0][0];
        Head->total = Data[1][0];
        Head->Next = NULL;
 
        Pointer = Head;
         
        for(i=1; i<MAX; i++){
            New = (Link)malloc(sizeof(Node));
            New->num = Data[0][i];
            New->total = Data[1][i];
            New->Next = NULL;
 
            Pointer->Next = New;
            Pointer = New;
        }
    }
     
    return Head;
}
 
void main()
{
    Link Head = Create_List(Head);
    Link New;
    int key;
 
    if(Head != NULL){
        Print_List(Head);

        while(1){
            printf("Input 0 to Exit\n");
            
            New = (Link) malloc(sizeof(Node));
            
            printf("Input data number:");
            scanf("%d", &New->num);
            
            if(New->num == 0)
                break;

            printf("Input data total:");
            scanf("%d", &New->total);

            printf("Input the data number for Insert:");
            scanf("%d", &key);

            Head = Insert_List(Head, New, key);

            Print_List(Head);
        }

        Free_List(Head);
    }
}


參考資料:
資料結構 黃國瑜/葉乃菁