链表的创建和遍历

/*链表的创建和建立*/




1.定义一个节点的数据类型

typedef struct Node
{
    int data;
    struct Node *pNext;
}NODE, *PNODE;


2.在主函数里创建链表并对其进行遍历

int main(void)
{
    PNODE pHead = NULL; //<=>struct Node *pHead = NULL
    pHead = create_list();
    traverse_list(pHead);
    return 0;
}


3.PNODE create_list()函数:创建链表

需要注意的是定义一个 pTail结构体指针,使这个结构体把存储的上一次的pNew->pNext指向本次的pNew之后,又把本次pNew的结构体指针赋给自己:pTail = pNew。

函数的返回值:返回头结点的指针。


4.void traverse_list(PNODE pHead)函数:遍历和打印链表

注意:传入要遍历和打印的头结点的指针


模块的C语言代码:

//list.c
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

typedef struct Node
{
    int data;
    struct Node *pNext;
}NODE, *PNODE;

static PNODE create_list(void);
static void traverse_list(PNODE pHead);

int main(void)
{
    PNODE pHead = NULL; //<=>struct Node *pHead = NULL
    pHead = create_list();
    traverse_list(pHead);
    return 0;
}

PNODE create_list(void)
{
    int i;
    int len;
    int val;

    PNODE pHead = NULL;
    PNODE pTail = NULL;
    PNODE pNew = NULL;

    pHead = malloc(sizeof(NODE));
    if (pHead == NULL)
    {
        printf("Allocation failure, Program termination");
        exit(-1);
    }

    pTail = pHead;
    pTail->pNext = NULL;

    printf("Please enter a number of linked list nodes that you want to build: len = ");
    scanf("%d", &len);

    for (i = 0; i < len; i++)
    {
        printf("Please enter the %d node value = ", i+1);
        scanf("%d", &val);

        pNew = malloc(sizeof(NODE));
        if (pNew == NULL)
        {
            printf("Allocation failure, Program termination!");
            exit(-1);
        }
        pNew->data = val;
        pTail->pNext = pNew;
        pNew->pNext = NULL;
        pTail = pNew;
    }

    return pHead;
}

void traverse_list(PNODE pHead)
{
    PNODE p = NULL;
    p = pHead;

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

    printf("\n");
    return;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值