RE: [Q] Is there any one good at linked lists - C 10-21-2017, 08:58 AM
#3
(10-20-2017, 06:33 PM)Altair Wrote: Help me please
I took a whirl at it, here's my code. I just modified what you had, and I didn't test it out, but anywhore, give this a shot. I made comments to help guide you.
I actually wrote a tutorial on making linked lists in C a while ago. You can find that tutorial at: https://sinister.li/Thread-Tutorial-C-Linked-list
Alternatively, I have a list of all my tutorials that you can browse through at https://sl.ipseitysoftware.com/ (it's also in my signature).
Feel free to ask my any questions.
I also added a pastebin link here with syntax highlighting on
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct liste
{
char * data;
struct liste * next;
};
// don't fucking typedef this shit, do it right
struct liste *head, *tail; //I renamed this to tail, since that's what it is, current sounds confusing
void add(char *); // add your function prototypes, even in small programs. Get into the habit
void clear(struct liste *) // recursive free memory
void add(char *chr)
{
struct liste *tmp = malloc(sizeof(struct liste));
tmp->data = strdup(chr); // don't forget that this is a c-string, so = is pointer equality
tmp->next = NULL;
if (tail == NULL)
{
// if the list has no elements yet, then this should be
// both the head, and our tail.
tail = head = tmp;
}
else
{
// the list already has elements
tail->next = tmp; // create the link in the list
tail = tmp; // advance our tail position
}
printf("word added: %s \t\t head: %s\n",tail->data,head->data);
}
void clear(struct liste *node)
{
if (node->next != NULL)
clear(node->next)
free(node->data);
free(node);
}
int main()
{ // always give the brace it's own line...it helps finding missing ones
/* variable definitions */ // always put these BEFORE any code or initializations, this is C
FILE *doysa;
char *c;
int i, slen;
/* initialize variables */
head = tail = NULL; // set up our empty list
/* program code */
if ((dosya = fopen("C:/Users/omerf/CLionProjects/untitled/Input1.txt","r")) == NULL) // file failed
{
printf("dosya acilamadi\n");
exit(-1); // i like to use negative failure numbers, -1 is also EOF
}
c = malloc(20); // allocate character buffer
while (!feof(dosya))
{
fscanf(dosya,"%s",c);
slen = strlen(c); // this will speed up your program by reducing memory operations
for(i = 0; i < slen; ++i)
{
if(!isalpha(c[i]))
c[i] = '\0'; // try to avoid same line if bodies..
}
add(c);
}
fclose(dosya);
/* deallocate memory */
free(c); // no longer need buffer
if (head != NULL) // if we have a list with entries
clear(head); // our recursive function will clean everything up for us nicely.
return 0;
}
(This post was last modified: 10-21-2017, 09:00 AM by phyrrus9.)



























![[+]](https://sinister.li/images/modern/collapse_collapsed.png)