c - 在C程序中打印链表

标签 c pointers linked-list printf

我看到过一些关于如何打印链接列表的其他帖子,但没有一个对我有帮助,所以我决定发布我自己的代码。问题是这样的:

我可以完美地添加姓名和年龄,但是当我添加另一个姓名和年龄时,它会覆盖前一个。

所以如果我输入:

Matt 和 21,然后是 charles 和 34。它只会输出 charles 和 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

}

哦,我知道一些“#include”可能没有用。我一整天都在添加和删除代码。

最佳答案

虽然您已经定义了 headend 指针(这将创建一个链接列表),但您实际上并没有使用它们来存储新信息。创建新节点并将其存储在 ptr 变量中后,您实际上并未将其存储在列表中。

我建议添加另一个方法,addnode,它将这个新创建的节点添加到由headend定义的链表中指针。

void addnode(struct node *ptr) {
    if (end == NULL) {
        head = ptr;
        end = ptr;
    }
    else {
        end = end->next = ptr;
    }
}

总的来说,我们检查列表中是否已有任何项目;如果不是,列表的开始和结束都将由同一个节点表示:列表中唯一的一个!否则,我们让当前结束之后的节点作为要添加的节点,然后将全局 end 指针移动到现在的最后一个节点。

这允许我们维护一个由多个节点(列表中的条目)组成的链。然后,在打印整个列表时,我们必须遵循整个链,从第一个节点 (head) 到最后一个节点。我们可以通过一个简单的循环来完成此操作:我们不是简单地在 main() 中维护的临时 ptr 变量上调用 printnode(),而是写:

struct node *current = head;
while (current != end) {
    printnode(current);
    current = current->next;
}

关于c - 在C程序中打印链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15932024/

相关文章:

c - gettimeofday 会导致 MPI 崩溃吗?

delphi - "Incompatible types: method pointer and regular procedure"

c - 无限循环和指针

c++ - C++如何从链表中选择随机项目

c - 将静态分配数组的地址获取到结构内的指针中

c - 一种Linked List但不完全理解

C:指向 malloc 堆位置的指针加 4

c - C : make function visible and callable through macro only (MSVC compiler) 中的函数可见性

iphone - '^' 标记之前存在语法错误

c - scanf 验证用户输入