現在我們用C語言實現一個鏈表,鏈表的結構大家都熟悉,也比較簡單,關鍵在於處理好頭指針和尾指針,指對地方,就沒什麼問題,來看源碼:
//創建一個鏈表
#include <stdio.h>
#include <stdlib.h>
//創建鏈表結構
struct list
{
int data;
struct list *next;
};
typedef struct list node;
typedef node *link;
int main()
{
link ptr,head;
int i,num;
//輸入鏈表中的元素
ptr = (link)malloc(sizeof(node));
head = ptr; //head 爲 頭指針
printf("Input 5 numbers :\n");
for (i = 0; i < 5; i++)
{
scanf("%d", &num);
ptr->data = num;
ptr->next = (link)malloc(sizeof(node));
if (i == 4) ptr->next = NULL;
else ptr = ptr->next;
}
//輸出鏈表
ptr = head;
while (ptr != NULL)
{
printf("%d\n", ptr->data);
ptr = ptr->next;
}
return 0;
}
list是結構體,node與它同類型,代表節點,而link代表指向節點的指針。malloc函數用來獲取內存