Def*_*c0n 2 c traversal linked-list nodes
我在创建链接列表时遇到了一些问题,还有一些我正在尝试的帮助函数.我的代码如下:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "getNextWord.h"
#define MAX_WORD_SIZE 256
typedef struct{
int counter;
char* key;
struct node* next;
} node;
node* createNode(char* words){
node* head;
if(!(head=malloc(sizeof(node)))) return NULL;
head->key=words;
head->next=NULL;
return head;
}
node* addToList(node* head, char* words){
node* newNode;
newNode=createNode(words);
newNode->next = head;
return newNode;
}
int find(node* head){
if (head->next != NULL){
node* next = head->next;
while(head != NULL){
if (strcmp(head->key,next->key)==0){
head->counter++;
head=head->next;
return 1;
}
else{
head=head->next;
}
}
}
return 0;
}
void printList(node* head){
node* pointer = head;
while (pointer != NULL){
printf("%s",pointer->key);
pointer=pointer->next;
}
printf("\n");
}
int main(int argc, char* argv[]){
if(argc<2){
fprintf(stderr, "Not enough arguments given\n");
}
for(int i=1; i< argc; i++){
FILE* fd=fopen(argv[i], "r");
if(fd != NULL){
char* words;
node* head = NULL;
while((words=getNextWord(fd)) != NULL){
find(head);
if (find(head) == 0){
createNode(words);
}
printList(head);
fprintf(stdout,"%s\n",words);
}
}
else(printf("No such file exists"));
fclose(fd);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我在互联网上环顾四周,似乎我正在关注大多数人对链表的看法.之前我没有收到任何错误,只是在以下函数中出现了一堆"警告:从不兼容的指针类型中分配":
addtolist (the line before the return)
find (before return one and the else line)
printlist (the last line in the while loop)
Run Code Online (Sandbox Code Playgroud)
我知道这不是那么好的代码,我不是最好的程序员,而只是想学习.此外,我的getnextword确实有效,但如果我需要它也可以发布.
你正在混合两个不同的"命名空间","标签"命名空间struct和相似的标识符命名空间typedef.最容易相处的是转发声明您要使用的类型:
typedef struct node node;
Run Code Online (Sandbox Code Playgroud)
然后你可以使用node或struct node互换.在里面
struct node {
// something
node * next;
};
Run Code Online (Sandbox Code Playgroud)