首页 > 解决方案 > 从单链表打印结构数据

问题描述

我正在尝试使用具有 2 种数据类型的结构来构建单链表:char*intnext当然也指向其他节点。

我有两个功能:addToListprintList以及运行一切的主要方法。

我的代码应该做的是在 之后添加一个节点head,并检查是否已经添加了另一个具有相同数据的节点。如果是这样,它不会添加新节点,同时增加count已链接节点的数据。

然后,printList()打印count数据和char*每个节点的数据。

第一个问题是我的 char 比较似乎不起作用,因为仍然添加了重复的节点。然后,我的printList函数无法正确打印 char* 数据。这是我的代码(我确保对其进行评论以便于理解):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Struct for node. Has an extra data variable to keep track of which node is next
// in a singly-linked list.
typedef struct node {
    char *str;
    unsigned int count;
    struct node *next;
} node;

// Creates a HEAD node with NULL data.
node *head = NULL;

// Adds a new node and populates the data.
struct node* addToList(struct node* Listptr, char* word){
    struct node* new = malloc(sizeof(struct node));
    new->str = malloc(sizeof(char) * 34);

    strcpy(new->str, word);

    new->count = 1;
    new->next = Listptr;

    // If the head is NULL, sets the new node as the head.
    if(head == NULL){
        head = new;
        return new;
    }

    // Sets a node iterator "cur" to the first position.
    node *cur = head;

    // Sets a node iterator to be one place behind cur.
    node *prev;

    // Loops through the linked list, in order to count the previous words and determine
    // if it is necessary to add another node.
    // Otherwise, it sets cur to the next node, and prev to the node cur was just at.
    while(cur != NULL){
        if(cur->str == new->str){
            cur->count++;
            new = NULL;
            return new;
        } else{
            prev = cur;
            cur = cur->next;
        }
    }

    // Checks to see if cur is NULL, if so, sets the previous node.next to the one we're adding.
    if(cur == NULL){
        prev->next = new;
        return new;
    }
}

// Prints out the count and word values of each node.
void printList(){
    node* cur = head;
    while(cur != NULL){
        printf("%d %c\n", cur->count, cur->str);
        cur = cur->next;
    }
}

int main() {

    node* Z = NULL;

    char *a = "hello";
    char *b = "world.";
    char *c = "hello";

    addToList(Z, a);
    addToList(Z, b);
    addToList(Z, c);

    printList(Z);

    return 0;
}

我希望得到:

2 hello
1 world

但在控制台中,我得到:

1 l
1 (weird symbol)
1 

标签: cpointersstructprintinglinked-list

解决方案


不要==用于比较字符串,而是使用strcmp().

改成if (cur->str == new->str)这样:

if (strcmp(cur->str, new->str) == 0)

阅读本文以了解有关字符串比较的更多信息:如何正确比较字符串?


推荐阅读