#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node * next;
};
//建立只含頭結點的空鏈表
struct Node * create_list()
{
struct Node * head = NULL;
head = (struct Node *)malloc(sizeof(struct Node));
if (NULL == head)
{
printf("memory out of use/n");
return NULL;
}
head->next = NULL;
head->data = 0;
return head;
}
//尾插法建立鏈表
int insert_form_tail(struct Node * head, int num)
{
struct Node * temp = head;
struct Node * new_node = NULL;
new_node = (struct Node *)malloc(sizeof(struct Node));
if (NULL == new_node)
{
printf("memory out of use/n");
return -1;
}
//尋找尾結點
while (temp->next != NULL)
{
temp = temp->next;
}
//將新結點插入到鏈表的最後
new_node->data = num;
new_node->next = NULL;
temp->next = new_node;
return 0;
}
//打印鏈表
int show_list(struct Node * head)
{
struct Node * temp;
temp = head->next;
while(temp)
{
printf("%d/n",temp->data);
temp = temp->next;
}
return 0;
}
int main(int argc, char* argv[])
{
struct Node * head;
head = create_list();
if (NULL == head)
printf("create_list error/n");
insert_form_tail(head,123);
insert_form_tail(head,456);
show_list(head);
}
計算機原理之c語言實現鏈表
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.