如何使用C語言建立一個單向連結清單
- 标題
#include<stdio.h>
#include<stdlib.h>
typedef struct list
{
int nValue;
struct list *pNext;
}List;
List *CreateList()
{
int num;
int value;
List *pHead = NULL;
List *pTemp = NULL;
List *pTail = NULL;
printf("請輸入節點個數\n");
scanf("%d",&num);
while(num!=0)
{
printf("請輸入節點值\n");
scanf("%d",&value);
pTemp = (List*)malloc(sizeof(List));
pTemp->nValue = value;
pTemp->pNext = NULL;
if(pHead == NULL)
{
pHead = pTemp;
}
else
{
pTail->pNext = pTemp;
}
pTail = pTemp;
num--;
}
return pHead;
}
void PrintList(List *pHead)
{
if(pHead)
{
printf("連結清單如下\n");
while(pHead != NULL)
{
printf("%d\n",pHead->nValue);
pHead = pHead->pNext;
}
}
}
int main()
{
List *pHead = CreateList();
PrintList(pHead);
return 0;
}
代碼如上,這裡連結清單節點隻設定了單個數值,讀者可根據需要進行更改。