C指针实现单链表---王晓东《数据结构与算法设计》

linkList.h

个人笔记,不喜勿喷,欢迎大佬指导

#include <malloc.h>
#define Error(module) fprintf(stderr,"error:"#module"\n")

typedef struct node *link;
typedef struct node {
    ListItem element;
    link next;
}Node;
link NewNode() { //生成新节点
    link p;
    if( (p=malloc(sizeof(Node)))==0 )
        Error("Exhausted memory.");
    else
        return p;
}

typedef struct llist *List;
typedef struct llist {
    link first;
}Llist;

List ListInit() {//初始化表
    List L = malloc(sizeof *L);
    L->first = 0;
    return L;
}
int ListEmpty(List L) {
    return L->first == 0;
}
int ListLength(List L) {//表长度
    int len = 0;
    link p;
    p = L->first;
    while(p) {
        len++;
        p = p->next;
    }
    return len;
}
ListItem ListRetrieve(int k, List L) { //查找第k个元素
    int i;
    link p;
    if( k<1 ) Error("out of bounds.");
    p = L->first;
    i = 1;
    while( i<k && p ) {
        p = p->next;
        i++;
    }
    return p->element;
}
int ListLocate(ListItem x, List L) { //查找数据 x
    int i=1;
    link p;
    p = L->first;
    while( p && p->element!=x ) { p = p->next; i++; }
    return p?i:0;
}
void ListInsert(int k, ListItem x, List L) {//在第k个位置加入x
    link p, y;
    int i;
    if( k<0 ) Error("out of bounds.");
    p = L->first;
    for( i=1; i<k && p; i++ ) p = p->next;
    y = NewNode();
    y->element = x;
    if( k ) {
        y->next = p->next;
        p->next = y;
    } else {
        y->next = L->first;
        L->first = y;
    }
}
void PrintList(List l) { //遍历链表
    for( int i=0; i<ListLength(l); i++ ) {
        Error("%d ", ListRetrieve(i+1, l) );
    }
}
ListItem ListDelete(int k, List L) { //删除第k个元素
    link p,q;
    ListItem x;
    int i;
    if( k<1 || !L->first ) Error("out of bounds.");
    p = L->first;
    if( k==1 )
        L->first = p->next;
    else {
        q = L->first;
        for( i=1; i<k-1 && q; i++ ) q = q->next;
        p = q->next;
        q->next = p->next;
    }
    x = p->element;
    free(p);
    return x;
}


猜你喜欢

转载自blog.csdn.net/qq_37131037/article/details/80426287