/*链表的创建和建立*/
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;
}