C中带有字符和整数的链表(疑难解答)



我想用C编写一个链表,尝试应用迄今为止学到的一切。我写这个程序是为了创建一个链表:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node *head = NULL;

//定义结构节点

struct node{
char * name;
int num;
struct node * next;
};

//打印列表

void printList(){
struct node * temp = head;
while (temp != NULL){
printf("%s", temp->name);
printf("%d", temp->num);
temp = temp->next;
}
}

//创建新节点

struct node * newNode (char * name, int num){
struct node * newNode = (struct node*)malloc(sizeof(struct node));
newNode->name = name;
newNode->num = num;
newNode->next = NULL;
return newNode;
}

//插入和排序元素的功能

void insertSorted (char * name, int num){
//Empty Liste -> Head is NULL
if (head == NULL){
head = newNode(name, num);
}
else if (strcmp(name, head->name) <=0){
// strcmp-output = -1 ->string 1 > string 2; 0 -> both strings are the same
struct node * temp = newNode(name, num);
temp->next = head;
head = temp;}
struct node * current = head; struct node *prev = NULL;
if (strcmp(name, current->name)>0){ //-> 1,  string1 < string 2 ->insert after
while(current != NULL && strcmp(name, current->name)<=0){
prev = current;
current = current->next;
}
struct node * temp = newNode(name, num);
prev->next = temp;
temp->next = current;
}
}

//链表测试

int main()
{
char name; int num;
//Testprogram
printf("Enter a namen");
scanf("%s", &name);
printf("Enter a numbern");
scanf("%d", &num);
insertSorted(&name, num);
char name2; int num2;
printf("Enter a namen");
scanf("%s", &name);
printf("Enter a numbern");
scanf("%d", &num2);
insertSorted(&name2, num2);*/
char name3; int num3;
printf("Enter a namen");
scanf("%s", &name);
printf("Enter a numbern");
scanf("%d", &num3);
insertSorted(&name3, num3);
printList();

return 0;
}

输出示例:

Input: Anna 1, Claudio 2, Berta 3
Output: 32Berta1

不知怎么的。。。使名称消失,数字也按错误的顺序排列。我对编程还很陌生,所以我很难自己解决这个问题。如果有任何帮助,我们将不胜感激:(不仅可以修复错误,还可以提供如何编程的提示。。。可以说是优雅。

谢谢:(

//编辑:

感谢您迄今为止的所有投入!我在测试程序时把字符串的输入搞砸了。

按照建议,我尝试跳过输入部分,在main((中测试这样的链表(谢谢Julien!(:

insertSorted("Anna", 1);
insertSorted("Claudio", 2);
insertSorted("Berta", 3);
printList();

它导致程序不执行并且以负数错误代码退出。这是否指向一个无限循环?

我还没有查看链接列表的详细信息,但我看到的一个问题是,您使用单个char变量来存储名称(应该是数组或字符(。由于缺乏足够的空间来存储输入,因此在调用scanf后,程序会出现未定义的行为。

正如@franji1所说,试着一步一步地工作。如果你想检查列表中的代码,请尝试测试:

insertSorted("Anna", 1);
insertSorted("Claudio", 2);
insertSorted("Berta", 3);

并检查结果是否符合您的预期。完成后,添加要求用户使用scanf输入的代码。

我不是C语言专家,但既然你提到了代码优雅,我可以告诉你这一点。您不需要使用所有这些不同的if语句,您可以从一开始就使用while循环,并在找到大于current的名称后插入。只要检查prev不为null,即使必须将其插入头节点之前,这也会起作用。我希望我帮了你,希望你能找到解决问题的办法!

最新更新