gpt4 book ai didi

c - C中遍历和打印单链表时出错

转载 作者:行者123 更新时间:2023-11-30 16:21:07 25 4
gpt4 key购买 nike

迷失了菜鸟,尝试逐行读取文件,即“一”、“二”、“三”并将其添加到有序链表中(我相信我已经工作了)。但是,我无法弄清楚 traverse_and_print 列表函数的语法/逻辑(并且不理解 *(转到此处并获取值)、&(获取地址)和 -> 。我主要工作的代码位于repl.it 位于 https://repl.it/@MichaelB4/DeafeningTreasuredMathematics

// A complete working C program to demonstrate all insertion methods 
// from https://www.geeksforgeeks.org/linked-list-set-2- inserting-a-node/

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

// Create structure for a linked list node

struct Node
{
const char *data;
struct Node *next;
};

struct Node *head;

// Given a reference (pointer to pointer) to the head of a list and a char*, appends a new node at the end
void append(struct Node** head_ref, const char *new_data)
{
// 1. allocate node
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

struct Node *last = *head_ref; // used in step 5

// 2. put in the data
new_node-> data = new_data;

// 3. Set new_node.next to Null, as it will be inserted at tail of list
new_node -> next = NULL;

// 4. If the Linked List is empty, then make the new node as head
if (*head_ref == NULL)
{
*head_ref = new_node;
//printf("head\n");
printf("%s", new_node -> data);
return;
}

// 5. Else traverse till the last node

while (last -> next != NULL)
last = last -> next;
printf("%s", new_node -> data);

// 6. Change the next of last node, have last node point to one just inserted, the new node at the end of the list, tail

last -> next = new_node;
return;
}

void traverse_and_printList(head){
struct Node* current = (struct Node*) malloc(sizeof(struct Node));
current = head;
while (head -> next != NULL)
printf("%s", current -> data);
current -> next = current;

}

/* Driver program to test above functions*/
int main()
{
// set up a file point to File to be opened
FILE* fp;
// holds contents of each line/word
char buffer[255];

fp = fopen("words.txt", "r");
if (fp == NULL)
{
fprintf(stderr, "Could not open infile");
return 2;
}

/* create an empty node */
struct Node* head = NULL;

int counter = 0;
char *head_value[255];

while(fgets(buffer, 255, (FILE*) fp)){
//printf("%s", buffer);
append(&head, buffer);
}

fclose(fp);
traverse_and_printList(head);
printf("\n");
return 0;
}

最佳答案

您对 current 指针的用途感到困惑。

首先,您不需要为其分配内存。您并不是想存储任何新内容。 current 指针只是一个帮助您在列表中的项目上移动的值。

其次,您不应修改列表的数据。 current->next = current 行是伪造的。它修改列表创建一个循环。不好。

第三,您的缩进表明您的 while 循环包含两个单独的语句,但没有 block 作用域( { ... }) 在他们周围。因此,只有第一个语句将成为循环的一部分。

最后,关于风格的一点。请不要在 -> 周围添加空格。虽然编译器不在乎,但它会使您的代码非常难以人类阅读。

正确遍历列表就像这样简单:

for(struct Node* current = head; current != NULL; current = current->next)
{
printf("%s\n", current->data);
}

关于c - C中遍历和打印单链表时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54993056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com