基礎版鏈表的例子
回顧下鏈表的創建 和 遍歷
/*
14點48分
鏈表
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
//定義了一個鏈表的數據類型
struct Node
{
int data;
struct Node* pNext;
};
typedef struct Node node;
//創建一個鏈表
node* CreateList()
{
int i, iLen, value;
node* pHead = NULL;
pHead = (node*)malloc(sizeof(node));
if (NULL == pHead)
{
printf("鏈表創建失敗\n");
return NULL;
}
node* pTail = pHead;
pTail->pNext = NULL;
printf("請輸入需要生成的鏈表節點的個數:len = ");
scanf("%d", &iLen);
for (i = 0; i < iLen; ++i)
{
printf("請輸入第%d個節點的值:", i + 1);
scanf("%d", &value);
node* pNode = (node*)malloc(sizeof(node));
if (pNode == NULL)
{
printf("分配失敗,程序終止!\n");
exit(-1);
}
pNode->data = value;
pNode->pNext = NULL;
pTail->pNext = pNode;
pTail = pNode; //爲下一次進入循環準備
}
return pHead;
}
//遍歷鏈表
void traverse_list(node* p)
{
node* pHead = p->pNext;
while (pHead != NULL)
{
printf("%d\n", pHead->data);
pHead = pHead->pNext;
}
}
int main()
{
struct Node* pHead; //定義頭節點
pHead = CreateList();
traverse_list(pHead);
return 0;
}