[英]Printing struct data from a singly-linked list
我正在嘗試使用具有 2 種數據類型的結構構建單鏈表: char*
和int
,當然還有next
指向其他節點。
我有兩個函數: addToList
和printList
以及運行所有內容的主要方法。
我的代碼應該做的是在head
之后添加一個節點,並檢查是否已經添加了另一個具有相同數據的節點。 如果是這樣,它不會添加新節點,同時增加已鏈接節點的count
數據。
然后, printList()
打印每個節點的count
數據和char*
數據。
第一個問題是我的 char 比較似乎不起作用,因為仍然添加了重復的節點。 然后,我的printList
function 無法正確打印 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
不要使用==
來比較字符串,而是使用strcmp()
。
if (cur->str == new->str)
更改為:
if (strcmp(cur->str, new->str) == 0)
閱讀本文以了解有關字符串比較的更多信息: 如何正確比較字符串?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.