我是鏈接LIsts的新手,我試圖在C中實現鏈表。 下面在我的代碼: -C中的鏈表實現C
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next;
};
void insert (struct node *head, int data);
void print (struct node *head);
int main()
{
struct node *head ;
head= NULL;
printf("new\n");
insert(head,5);
printf("%d\n",head);
insert(head,4);
insert(head,6);
print(head);
print(head);
print(head);
}
void insert(struct node *head,int data){
printf("%d\n",head);
if(head == NULL){
head =malloc(sizeof(struct node));
head->next = NULL;
head->data = data;
}
else {
printf("entered else\n");
struct node *tmp = head;
if(tmp->next!=NULL){
tmp = tmp->next;
}
tmp->next = malloc(sizeof(struct node));
tmp->next->next = NULL;
tmp->next->data = data;
}
}
void print (struct node *head) {
printf("%d\n",head);
struct node *tmp = head;
if (head == NULL) {
printf("entered null\n");
return;
}
while (tmp != NULL) {
if (tmp->next == NULL) {
printf("%0d", tmp->data);
} else {
printf("%0d -> ", tmp->data);
}
tmp = tmp->next;
}
printf("\n");
}
當我運行這段代碼的輸出是: -
new
0
0
0
0
0
entered null
0
entered null
0
entered null
頭總是空和它不更新空。它不會在insert中進入else循環。 任何人都可以幫助我解決這個問題。指出我正在做的錯誤。 謝謝
在網絡上的C教程中必須有一個萬億的鏈表。爲什麼不從其中一個開始,然後修改它以滿足您的要求? Google上的熱門點擊之一是http://www.cprogramming.com/tutorial/c/lesson15.html – 2014-09-11 06:33:45
「插入」功能提示問題。 – user1336087 2014-09-11 06:36:51