C语言写简单的单项链表

2020-08-31 15:00:28 浏览数 (1)

代码语言:javascript复制
/* 基本数据结构的定义以及函数的声明 */
typedef int ElemType;

typedef struct Node
{
    ElemType elem;
    struct Node* next;
} Node, * NodePtr, **ForwardList;

NodePtr createNode(ElemType x);

void showList(ForwardList lst);

void destroyList(ForwardList lst);

// 创建元素为x的节点并插入到节点where后面
// 若where为NULL, 则插入到链表lst的首部作为首节点
// 返回新节点的指针
NodePtr insertAfterNode(NodePtr where, ElemType x,
        ForwardList lst);
代码语言:javascript复制
/* 链表相关函数的具体实现 */
NodePtr createNode(ElemType x)
{
    NodePtr pNode = (NodePtr) malloc(sizeof(Node));
    if (pNode == NULL) {
        perror("malloc");
        exit(1);
    }

    pNode->elem = x;
    pNode->next = NULL;
    return pNode;
}

NodePtr insertAfterNode(const NodePtr where,
        ElemType x, ForwardList lst)
{
    NodePtr pNode = createNode(x);

    if (where == NULL) {
        *lst = pNode;
    } else {
        pNode->next = where->next;
        where->next = pNode;
    }

    return pNode;
}

void showList(ForwardList lst)
{
    printf("显示链表: ");
    NodePtr curr = *lst;
    while (curr->next != NULL) {
        printf("%d->", curr->elem);
        curr = curr->next;
    }
    printf("%dn", curr->elem);
}

void destroyList(ForwardList lst)
{
    printf("销毁链表: ");
    NodePtr curr = *lst;
    while (curr != NULL) {
        NodePtr next = curr->next;
        printf("%d ", curr->elem);
        free(curr);
        curr = next;
    }
    printf("n");
}

0 人点赞