데이터 구조 선형 표 의 체인 저장 (순수 코드)

데이터 구조 선형 표 의 체인 저장 (순수 코드)
#include
#include
#define ERROR 0
#define OK 1
#define TRUE 1
#define FALSE 0

typedef int datatype;//    
typedef int status;//   
typedef struct Node{
     
    datatype data;
    struct Node *next;
}Node;
typedef struct Node *LinkList;//  linklist
//   
status initlist(LinkList *L){
     
    *L = (LinkList)malloc(sizeof(Node));
    if(!(*L)){
     
        return ERROR;
    }
    (*L)->next = NULL;
    return OK;
}
//  
status ClearList(LinkList *L){
     
    LinkList p,q;
    p = (*L)->next;
    while(p){
     
        q = p->next;
        free(p);
        p = q;
    }
    (*L)->next = NULL;
    return OK;
}
//      
int ListLength(LinkList L){
     
    int i=0;
    LinkList p = L->next;
    while(p){
     
        i++;
        p = p->next;
    }
    return i;
}
//   
void CreateListHeader(LinkList *L,int n){
     
    LinkList p;
    int i;
    (*L)->next = NULL;
    for(i=0;i<n;i++){
     
        p = (LinkList)malloc(sizeof(Node));
        p->data = i;
        p->next = (*L)->next;
        (*L)->next = p;
    }
}
//   
void CreateListTail(LinkList *L,int n){
     
    LinkList p,r;
    int i;
    *L = (LinkList)malloc(sizeof(Node));
    r = *L;
    for(i=0;i<n;i++){
     
        p = (LinkList)malloc(sizeof(Node));
        p->data = i;
        r->next = p;
        r = p;
    }
    r->next = NULL;
}
//       
status GetElem(LinkList L,int i,datatype *e){
     
    LinkList p;
    int j = 1;
    p  = L->next;
    while(p&&j<i){
     
        p = p->next;
        ++j;
    }
    if(!p||j>i){
     
        return ERROR;
    }
    *e = p->data;
    return OK;
}
//      
status DelElem(LinkList *L,int n){
     
    LinkList p,q;
    p = *L;
    int j = 1;
    while(p->next&&j<n){
     
        p = p->next;
        ++j;
    }
    if(!(p->next)||j>n){
     
        return ERROR;
    }
    q = p->next;
    p->next = q->next;
    free(q);
    return OK;
}
//  
status InsertList(LinkList *L,int n,datatype x){
     
    int i=1;
    LinkList p,q;
    p = *L;
    while(p->next&&i<n){
     
        p = p->next;
        ++i;
    }
    if(!(p->next)||i>n){
     
        return ERROR;
    }
    q = (LinkList)malloc(sizeof(Node));
    q->next = p->next;
    p->next = q;
    return OK;
}
int main(){
     
    LinkList L;
    initlist(&L);
    int length;
    CreateListHeader(&L,10);
    length = ListLength(L);
    printf("(   )     :%d
"
,length); ClearList(&L); length = ListLength(L); printf(" :%d
"
,length); CreateListTail(&L,10); length = ListLength(L); printf("( ) :%d
"
,length); // datatype num; GetElem(L,5,&num); printf(" :%d
"
,num); // DelElem(&L,4); length = ListLength(L); printf(" :%d
"
,length); // InsertList(&L,4,3); length = ListLength(L); printf(" :%d
"
,length); }

좋은 웹페이지 즐겨찾기