程序来自于郝斌数据结构与算法课程链表部分。

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


typedef struct Node {

    int data;

    struct Node* pNext;

}NODE, *PNODE;

PNODE create_list();

void traverse_list();

void main() {

    PNODE pHead = NULL;

    pHead = create_list();//创建一个非循环单链表

    traverse_list(pHead);//遍历输出

}

PNODE create_list() {

    int len = 0;
    int val= 0;
    PNODE pHead = (PNODE)malloc(sizeof(NODE));
    
    if (pHead == NULL) {

        printf("内存分配失败,程序将自动退出。");
        exit(-1);

    }

    PNODE pTail = pHead;
    pTail->pNext = NULL;

    printf("请输入您要生成链表节点的个数:");
    scanf_s("%d", &len);

    for (int i = 0; i < len; ++i) {

        printf("请输入第%d节点的值:",i+1);
        scanf_s("%d", &val);

        PNODE pNew = (PNODE)malloc(sizeof(NODE));
        if (pNew == NULL) {

            printf("内存分配失败,程序将自动退出。");
            exit(-1);

        }
        pNew->data = val;
        pTail->pNext = pNew;
        pNew->pNext = NULL;
        pTail = pNew;
    }
    return pHead;
}

void traverse_list(PNODE pHead) {

    PNODE p = (PNODE)malloc(sizeof(NODE));

    p = pHead->pNext;
    while (p != NULL)
    {
        printf("%d", p->data);
        p = p->pNext;
    }
}