我已經看到一些關於如何打印鏈表的其他文章,但沒有一篇對我有幫助,因此我決定發佈自己的代碼。這是問題:在C程序中打印鏈表
我能夠添加一個名字和年齡完全正常,但第二個我添加另一個名稱和年齡它覆蓋了前一個。
所以,如果我輸入:
馬特和21,然後查爾斯和34也只會輸出查爾斯和34 我如何得到它輸出的一切嗎? 非常感謝您的幫助! :)
這裏是我的代碼:
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#define pause system ("pause")
// prototype variables
struct node * initnode(char*, int);
void printnode(struct node*);
struct node{
char name[20];
int age;
struct node *next;
};
struct node *head = (struct node*) NULL;
struct node *end = (struct node*) NULL;
struct node* initnode(char *name, int age){
struct node *ptr;
ptr = (struct node*) calloc(3, sizeof(struct node));
if(ptr == NULL)
return (struct node*) NULL;
else {
strcpy(ptr->name, name);
ptr->age = age;
return ptr;
}
}
void printnode(struct node *ptr) {
printf("Name -> %s\n", ptr->name);
printf("Age -> %d\n", ptr->age);
}
main() {
char name[20];
int age, choice = 1;
struct node *ptr;
while(choice != 3){
system("cls");
printf("1. Add a name\n");
printf("2. List nodes\n");
printf("3. Exit");
printf("\nEnter Menu Selection: ");
scanf("%d", &choice);
switch(choice) {
case 1: printf("\nEnter a name: ");
scanf("%s", name);
printf("Enter age: ");
scanf("%d", &age);
ptr = initnode(name, age);
break;
case 2: if(ptr == NULL) {
printf("Name %s not found\n", name);
} else
printnode(ptr);
pause;
break;
case 3: exit(3);
default: printf("Invalid Entry");
}// end of switch
}// end of main
}
哦,我知道了一些「#包括的」可能不是很有用。我一直在添加和刪除代碼。
它看起來不像你正在建造鏈表。例如,「head」和「end」從未被引用。 – 2013-04-10 17:02:50
呵呵,你不需要在C程序中輸入'malloc'的返回值。除此之外,什麼是所有的'NULL'的轉換? – 2013-04-10 17:03:47
你的鑄造是正確的,你不需要在C編程中明確施放,完好無損它**可能**會導致錯誤一段時間......但這也是**不是你的答案** – 2013-04-10 17:07:35