具有3個有效結點的鏈表結構,如下圖所示:
 #include <stdio.h>
#include <malloc.h> //包含malloc函數
#include <stdlib.h> //包含exit函數
typedef struct Node
{
int data; //數據域
struct Node * pNext; //指針域
}NODE, *PNODE; //NODE等價於struct Node, PNODE等價於struct Node *
//函數聲明
PNODE creat_list(void);
int main(void)
{
PNODE pHead = NULL; //等價於struct Node * pHead = NULL
pHead = creat_list(); //創建一個非循環單鏈表
return 0;
}
PNODE creat_list(void)
{
int len; //鏈表的節點個數
int i;
int val; //臨時存放用戶數據
PNODE pHead = (PNODE)malloc(sizeof(NODE)); //分配了一個不存放有效數據的頭節點
if (NULL == pHead)
{
printf("分配失敗!程序終止!");
exit(-1);
}
PNODE pTail = pHead;
pTail->pNext = NULL;
printf("請輸入鏈表節點個數:len = ");
scanf("%d", &len);
for (i = 0; i < len; i++)
{
printf("請輸入第%d個節點的值:", i+1);
scanf("%d", &val);
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew)
{
printf("分配失敗!程序終止!");
exit(-1);
}
pNew->data = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}