【发布时间】:2019-03-04 23:14:48
【问题描述】:
Lost Noob,试图逐行读取文件,即“一”、“二”、“三”并将其添加到有序链表(我相信我已经在工作)。但是,我无法弄清楚我的 traverse_and_print 列表函数的语法/逻辑(并且不明白 *(go to here and get value)、&(get address) 和 -> 很好。我的主要工作代码是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;
}
【问题讨论】:
标签: c pointers printing linked-list