I'm getting segmentation fault when trying to access current_nap->next (sometimes even on current->value->napok but that's rare). I don't get why this happens because I can iterate through NapList with the functions in its header without any problem. Could you help me, please?
Here is my code:
void saveToFile()
{
int g;
g = open("save.dat", O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
JelentkezesList *current = jelentkezesek;
char line[] = "";
while (current != NULL)
{
printf("eddig ok\n");
strncpy(line, "", sizeof(line));
printf("eddig ok2\n");
strcat(line, "{");
strcat(line, current->value->nev);
strcat(line, ";");
strcat(line, current->value->cim);
strcat(line, ";");
printf("eddig ok3\n");
NapList *current_nap = current->value->napok;
printf("eddig ok4\n");
while (current_nap != NULL)
{
printf("eddig ok5\n");
if (current_nap->value == HETFO)
{
strcat(line, "0");
printf("hetfo\n");
}
else if (current_nap->value == KEDD)
{
strcat(line, "1");
printf("kedd\n");
}
else if (current_nap->value == SZERDA)
{
strcat(line, "2");
printf("szerda\n");
}
else if (current_nap->value == CSUTORTOK)
{
strcat(line, "3");
printf("csutortok\n");
}
else if (current_nap->value == PENTEK)
{
strcat(line, "4");
printf("pentek\n");
}
else if (current_nap->value == SZOMBAT)
{
strcat(line, "5");
printf("szombat\n");
}
else if (current_nap->value == VASARNAP)
{
strcat(line, "6");
printf("vasarnap\n");
}
printf("eddig ok5.1\n");
//if (current_nap->next != NULL)
//{
strcat(line, ",");
//}
printf("eddig ok6\n");
current_nap = current_nap->next;
printf("eddig ok7\n");
}
strcat(line, "}\n");
if (write(g, line, sizeof(line)) != sizeof(line))
{
printf("Hiba a mentés során!");
exit(1);
}
printf("eddig ok8\n");
current = current->next;
printf("eddig ok9\n");
}
close(g);
printf("%s", "Sikeres mentés!");
}
Here are my headers:
JelentkezesList
#include "string_utils.h"
#include "jelentkezes.h"
#include "nap_list.h"
#ifndef JELENTKEZES_LIST_H
#define JELENTKEZES_LIST_H
typedef struct jelentkezes_node
{
Jelentkezes *value;
struct jelentkezes_node *next;
} JelentkezesList;
void printJelentkezesList(JelentkezesList *head)
{
JelentkezesList *current = head;
while (current != NULL)
{
printf("\n");
printJelentkezes(current->value);
current = current->next;
}
}
void printJelentkezesListForDay(JelentkezesList *head, Nap nap)
{
JelentkezesList *current = head;
while (current != NULL)
{
if (containsNap(current->value->napok, nap))
{
printf("\n");
printJelentkezes(current->value);
}
current = current->next;
}
}
void addToJelentkezesList(JelentkezesList **list, Jelentkezes *value)
{
JelentkezesList *current = *list;
if (current == NULL)
{
current = (JelentkezesList *)malloc(sizeof(JelentkezesList));
Jelentkezes *j = value;
j->azonosito = 0;
current->value = j;
current->next = NULL;
*list = current;
}
else
{
while (current->next != NULL)
{
current = current->next;
}
current->next = (JelentkezesList *)malloc(sizeof(JelentkezesList));
Jelentkezes *j = value;
j->azonosito = current->value->azonosito + 1;
current->next->value = j;
current->next->next = NULL;
}
}
Jelentkezes *findJelentkezes(JelentkezesList *list, int id)
{
Jelentkezes *result = NULL;
JelentkezesList *current = list;
while (current != NULL && result == NULL)
{
if (current->value->azonosito == id)
{
result = current->value;
}
current = current->next;
}
return result;
}
void deleteJelentkezes(JelentkezesList **list, Jelentkezes *j)
{
JelentkezesList *current = *list;
if (current->value->azonosito == j->azonosito)
{
*list = current->next;
free(current);
return;
}
while (current->next->value->azonosito != j->azonosito)
{
current = current->next;
}
JelentkezesList *toDelete = current->next;
current->next = current->next->next;
free(toDelete);
*list = current;
}
JelentkezesList *createJelentkezesList()
{
JelentkezesList *jelentkezes_head = NULL;
return jelentkezes_head;
}
#endif
Jelentkezes
#include "string_utils.h"
#include "nap.h"
#include "nap_list.h"
#include <stdio.h>
#include <string.h>
#ifndef JELENTKEZES_H
#define JELENTKEZES_H
typedef struct
{
int azonosito;
String nev;
String cim;
NapList *napok;
} Jelentkezes;
Jelentkezes *createJelentkezes(String *nev, String *cim, NapList *napok)
{
Jelentkezes *j = (Jelentkezes *)malloc(sizeof(Jelentkezes));
j->azonosito = -1;
j->nev = *nev;
j->cim = *cim;
j->napok = napok;
return j;
}
void printJelentkezes(Jelentkezes *j)
{
printf("Azonosító: %d\n", j->azonosito);
printf("Név: %s, Cím: %s\n", j->nev, j->cim);
printf("Munkavállalás napjai: ");
printNapList(j->napok);
}
#endif
NapList
#include "string_utils.h"
#include "nap.h"
#include <stdbool.h>
#ifndef NAP_LIST_H
#define NAP_LIST_H
typedef struct nap_node
{
Nap value;
struct nap_node *next;
} NapList;
void printNapList(NapList *head)
{
NapList *current = head;
while (current != NULL)
{
if (current->value == HETFO)
{
printf("hétfő");
}
else if (current->value == KEDD)
{
printf("kedd");
}
else if (current->value == SZERDA)
{
printf("szerda");
}
else if (current->value == CSUTORTOK)
{
printf("csütörtök");
}
else if (current->value == PENTEK)
{
printf("péntek");
}
else if (current->value == SZOMBAT)
{
printf("szombat");
}
else if (current->value == VASARNAP)
{
printf("vasárnap");
}
if (current->next != NULL)
{
printf(", ");
}
current = current->next;
}
printf("\n");
}
void addToNapList(NapList **list, Nap value)
{
NapList *current = *list;
if (current == NULL)
{
current = (NapList *)malloc(sizeof(NapList));
current->value = value;
current->next = NULL;
*list = current;
}
else
{
while (current->next != NULL)
{
current = current->next;
}
current->next = (NapList *)malloc(sizeof(NapList));
current->next->value = value;
current->next->next = NULL;
}
}
bool containsNap(NapList *nl, Nap nap)
{
NapList *current = nl;
while (current != NULL)
{
if (current->value == nap)
return true;
current = current->next;
}
return false;
}
NapList *createNapList()
{
NapList *nap_head = NULL;
return nap_head;
}
#endif
Related
In the main function, I tried to push front couple numbers and push back couple numbers and then remove pos = 0 and pso = 1. However, in the output, remove at pos = 0 and remove at pos = 1 prints out number 5 and number 7 which are wrong. It should be 4 and 2. I cannot find which part I am wrong. Here is my code:
#ifndef MYDLL_H
#define MYDLL_H
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
struct node *previous;
} node_t;
typedef struct DLL
{
int count;
node_t *head;
node_t *tail;
} dll_t;
dll_t *create_dll()
{
dll_t *myDLL = (dll_t*)malloc(sizeof(dll_t));
if (myDLL == NULL) {
return NULL;
}
myDLL->count = 0;
myDLL->head = NULL;
myDLL->tail = NULL;
return myDLL;
}
int dll_empty(dll_t *l)
{
if (l == NULL) {
return -1;
}
if (l->count == 0 && l->head == NULL) {
return 1;
} else {
return 0;
}
}
int dll_push_front(dll_t *l, int item)
{
if (l == NULL) {
return -1;
}
node_t* new = (node_t*)malloc(sizeof(node_t));
if (new == NULL) {
return -1;
}
new->data = item;
new->next = l->head;
new->previous = NULL;
if (l->head != NULL) { //set new prev for the previous head before pushing.
l->head->previous = new;
}
l->head = new; // reset the new head for l.
l->count++;
return 1;
}
int dll_push_back(dll_t *l, int item)
{
if (l == NULL) {
return -1;
}
node_t* new = (node_t*)malloc(sizeof(node_t));
if (new == NULL) {
return -1;
}
new->data = item;
new->previous = l->tail;
new->next = NULL;
if(l->tail != NULL) {
l->tail->next = new;
} else {
l->head = new;
}
l->tail = new;
l->count++;
return 1;
}
int dll_pop_front(dll_t *t)
{
if (t == NULL || t->head == NULL) {
return -1;
}
node_t* pop_pointer = t->head;
int pop_item = pop_pointer->data;
t->head = pop_pointer->next; // set new head.
if (t->head != NULL) {
t->head->previous = NULL;
} else { // t->head = NULL cuz only one item and after popping, the t->head is null.
t->tail = NULL; // else if t->head = NULL, then t->tail also should be NULL.
}
if (t->head == NULL) {
t->tail = NULL;
}
t->count--;
free(pop_pointer);
return pop_item;
}
int dll_pop_back(dll_t *t)
{
if (t == NULL || t->head == NULL) {
return -1;
}
node_t* pop_pointer = t->tail;
int pop_item = pop_pointer->data;
t->tail = pop_pointer->previous;
if (t->tail != NULL) {
t->tail->next = NULL;
} else {
t->head = NULL;
}
if (t->head == NULL) {
t->tail = NULL;
}
t->count--;
free(pop_pointer);
return pop_item;
}
int dll_insert(dll_t *l, int pos, int item)
{
if (l == NULL) {
return -1;
}
if (pos >= l->count || pos < 0) {
return 0;
}
node_t* new = (node_t*)malloc(sizeof(node_t));
if (new == NULL) {
return 0;
}
new->data = item;
if(pos == 0) {
return dll_push_front(l, item);
}
node_t* pointer = l->head;
for (int i = 0; i < pos - 1; i++) {
pointer = pointer->next;
}
//ex: pos = 1, no for loop, pointer still head.
new->previous = pointer;
new->next = pointer->next;
pointer->next->previous = new;
pointer->next = new;
l->count++;
return 1;
}
int dll_get(dll_t *l, int pos)
{
if (l == NULL) {
return -1;
}
if (pos < 0 || pos >= l->count) {
return 0;
}
node_t* pointer = l->head;
for (int i = 0; i < pos - 1; i++) {
pointer = pointer->next;
}
return pointer->data;
}
int dll_remove(dll_t *l, int pos)
{
if (l == NULL) {
return -1;
}
if (pos < 0 || pos >= l->count) {
return 0;
}
node_t* pointer = l->head;
node_t* prev = NULL; // first node prev is null.
for (int i = 0; i < pos; i++) {
prev = pointer;
pointer = pointer->next;
}
if (prev == NULL) { // first item.
l->head = pointer->next;
} else {
prev->next = pointer->next;
}
if (pointer->next != NULL) {
pointer->next->previous = prev;
}
// if we are removing the tail node
if (pointer == l->tail) {
l->tail = prev;
}
int removed_value = pointer->data;
free(pointer);
l->count--;
return removed_value;
}
int dll_size(dll_t *t) {
if (t == NULL) {
return -1;
}
return t->count;
}
void free_dll(dll_t *t)
{
if (t == NULL) {
return;
}
if (t == NULL) {
free(t);
return;
}
node_t* pointer = t->head;
while(pointer != NULL) {
node_t* pointer2 = pointer;
pointer = pointer->next;
free(pointer2);
}
free(t);
}
#endif
Here is my code for generating a GLL for the string input: a,(b,c),d where (b,c) will be linked as a child at the next link of a.
GLL* generateList(char poly[])
{
GLL* newNode = NULL, *first = NULL, *ptr = NULL;
while (poly[i] != '\0')
{
if (poly[i] == ')')
{
return first;
}
else
{
if (poly[i] != ',')
{
if (poly[i] != '(')
{
newNode = createNode(poly[i], 0);
}
else
{
++i;
newNode = createNode('#', 1);
newNode->dlink = generateList(poly);
}
}
}
if (first != NULL)
{
ptr = first;
while (ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = newNode;
}
else
{
first = newNode;
}
i++;
}
return first;
}
And here is the structure I used for each node.
typedef struct gll
{
int tag;
struct gll* next;
char data;
struct gll* dlink;
} GLL;
I am not finding a way to add that child link to the parent link whenever the bracket opens. The programs runs in a loop.
Note: I have declared i=0 as a global variable to hold the position of character.
Edit: Here is the createNode function
GLL* createNode(char value, int flag)
{
GLL* newNode;
newNode = (GLL *) malloc(sizeof(GLL)*1);
newNode->data = value;
newNode->dlink = NULL;
newNode->tag = flag;
newNode->next = NULL;
return newNode;
}
How do I do it then?
You could do something like that:
#include <stdbool.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct gll
{
int tag;
struct gll* next;
char data;
struct gll* dlink;
} GLL;
GLL* createNode(char value, int flag)
{
GLL* newNode = calloc(1, sizeof(*newNode));
if (!newNode)
return NULL;
newNode->tag = flag;
newNode->data = value;
return newNode;
}
void freeList(GLL *list)
{
for (GLL *current_node = list, *temp; current_node; current_node = temp) {
temp = current_node->next;
freeList(current_node->dlink);
free(current_node);
}
}
GLL* generateList(char *poly, size_t *pos)
{
size_t const length = strlen(poly);
GLL *head = NULL;
GLL *tail = NULL;
for (; *pos < length; ++*pos) {
if (poly[*pos] == '(') {
++*pos; // don't have the next called generateList() read '(' again
tail->dlink = generateList(poly, pos);
if (!tail->dlink) {
freeList(head);
return NULL;
}
continue;
}
else if (poly[*pos] == ')') {
return head;
}
else if (isalpha((char unsigned)poly[*pos])) {
if (!head) {
head = tail = createNode(poly[*pos], 0);
}
else {
tail->next = createNode(poly[*pos], 0);
tail = tail->next;
}
continue;
}
else if (poly[*pos] == ',')
continue;
fputs("Format error :(\n\n", stderr);
freeList(head);
return NULL;
}
return head;
}
void printList(GLL *list)
{
for (GLL *node = list; node; node = node->next) {
printf("%c ", node->data);
if (node->dlink) {
putchar('(');
printList(node->dlink);
printf("\b) ");
}
}
}
int main(void)
{
size_t pos = 0;
GLL *list = generateList("a,(b,(c,d,e(f)),g,h),i,j,k", &pos);
printList(list);
putchar('\n');
freeList(list);
}
Output
a (b (c d e (f)) g h) i j k
Also, if flag is true then it means that the data is not to be considered but there is a child list to be linked.
Sorry, but I don't get how there could be a child list if there is no data for the node.
I tried to implement circular linked list to manage a set of tasks by a server side application. The application is multi-threaded where one thread (updater() ) reads the linked list only for read while another two (push_stream() and delete_stream()) access the linked list to add to and delete from the linked list respectively.
My problem is not all the files to be deleted (after being processed) are deleted.
struct data_stream
{
bool processed;
int count;
char filename[30];
int TYPE_GRP;
int task_type;
struct data_stream *next;
};
struct data_stream *stream_head=NULL; //global variable
main(partial code)
main()
{
_beginthread(updater, 0, NULL);
while ((new_socket = accept(srv_sock, (struct sockaddr *)&client, &c)) != INVALID_SOCKET)
{
_beginthreadex(0, 0, handle_client, &new_socket, 0, 0);
}
}
handle_client function (partial code)
handle_client()
{
//some where in handle_client
EnterCriticalSection(&stream_lock);
stream_head = push_stream(&stream_head, TYPE_GRP, task_type);
LeaveCriticalSection(&stream_lock);
}
updater function (full source code)
void updater(void *data)
{
while (1)
{
struct data_stream*temp = stream_head;
struct data_stream*first = stream_head;
struct data_stream*prev = NULL;
if (stream_head != NULL)
{
struct data_stream*next = NULL;
do
{
next = temp->next;
if (temp->processed == false&&temp->task_type == 2)
{
process_files(temp);
}
else if (temp->processed == false&&temp->task_type == 3)
{
process_others();
}
EnterCriticalSection(&stream_lock);
temp->processed = true;
LeaveCriticalSection(&stream_lock);
temp = next;
} while (temp != first);
}
if (stream_head != NULL)
{
EnterCriticalSection(&stream_lock);
stream_head=delete_stream(&stream_head);
LeaveCriticalSection(&stream_lock);
}
Sleep(6000);
}
}
process_files
void process_files(struct data_stream*temp)
{
int count = 0;
char file_to_update[50] = { NULL };
size_t name_len = strlen(temp->filename);
memcpy_s(file_to_update, name_len, temp->filename, name_len);
file_to_update[name_len] = '\0';
temp->count = 0;
FILE *list_to_update ;
fopen_s(&list_to_update , file_to_update, "r+b");
if (list_to_update != NULL)
{
char readline[100] = { '\0' };
while (fgets(readline, sizeof(readline), list_to_update ) != NULL)
{
//read a line at a time and process the list
count++;
}
temp->count = count;
fclose(list_to_update );
}
else
printf("\nerror opening file\n");
}
process_others()
void process_others(struct data_stream*temp)
{
int count = 0;
char file_to_update[50] = { NULL };
size_t name_len = strlen(temp->filename);
memcpy_s(file_to_update, name_len, temp->filename, name_len);
file_to_update[name_len] = '\0';
temp->count = 0;
FILE *list_to_update ;
fopen_s(&list_to_update , file_to_update, "r+b");
if (list_to_update != NULL)
{
char readline[100] = { '\0' };
while (fgets(readline, sizeof(readline), list_to_update ) != NULL)
{
//read a line at a time and process the list
count++;
}
temp->count = count;
fclose(list_to_update );
}
else
{
printf("\nerror opening file\n");
}
}
}
push_stream (full source code)
struct data_stream* push_stream(struct data_data_stream**head_ref, int typ_grp, int task_type)
{
struct data_stream*new_data_stream=
(struct data_data_stream*)malloc(sizeof(struct data_stream));
new_stream->processed = false;
new_stream->task_type = task_type;
new_stream->TYPE_GRP = typ_grp;
new_stream->filename[0] = NULL;
new_stream->count = 0;
new_stream->next = NULL;
if (task_type == 2)
sprintf_s(new_stream->filename, "%s%03d.txt", "file_md5_list_", stream_count);
else
sprintf_s(new_stream->filename, "%s%03d.txt", "other_list_", stream_count);
if (*head_ref == NULL)
{
*head_ref = new_stream;
new_stream->next = new_stream;
}
else
{
struct data_stream* last = (*head_ref)->next;
struct data_stream* prev = (*head_ref)->next;
while (last != *head_ref)
{
prev = last;
last = last->next;
}
new_stream->next = *head_ref;
last->next = new_stream;
}
if (stream_count > 998)
stream_count = 1;
else
stream_count++;
return new_stream;
}
delete_stream function (full source code)
struct data_stream* delete_stream(struct data_data_stream**head)
{
if (head == NULL)
return NULL;
struct data_stream*prev = NULL;
struct data_stream*temp = *head;
struct data_stream*first = *head;
do
{
struct data_stream*next = temp->next;
if (temp->processed)
{
if (prev == NULL)
*head = temp->next;
else
prev->next = temp->next;
char file_to_delete[50] = { NULL };
memcpy_s(file_to_delete, strlen(temp->filename), temp->filename, strlen(temp->filename));
DeleteFileA(file_to_delete);
free(temp);
}
else
{
prev = temp;
}
temp = next;
} while (temp != first);
if (prev == NULL)
{
return NULL;
}
return *head;
}
i have a simple linked list with a string, int, and next pointer in each node.
all the other linked list functions works (pop, push, delete node, etc.), but the reverse function just duplicate my node.
here is my code:
personNode* reverseList(personNode* head)
{
personNode* curr = head;
personNode* previous = NULL;
personNode* next = NULL;
while (curr != NULL)
{
next = curr->next;
curr->next = previous;
previous = curr;
curr = next;
}
head = previous;
printf("Line reversed!");
return head;
}
the results are:
Before "reversing":
and after:
(Here is The whole code:)
#include <stdio.h>
#define STR_LEN 21
typedef struct personNode
{
char name[STR_LEN];
int age;
char friends[3][STR_LEN];
struct personNode* next;
}personNode;
int recursiveLength(personNode* head, int counter);
void createPerson(char name[], int age, char friends[3][STR_LEN], personNode* head);
void link(personNode* head, personNode* toLink);
char* iHaveFriends(personNode* guest, personNode* head);
int addBehindFriend(char* friendName, personNode* guest, personNode* head);
void removePersonByName(char name[], personNode* head);
void addToListTop(personNode* VIP, personNode* head);
void search(personNode* head, char name[]);
personNode* reverseList(personNode* head);
void freeList(personNode* head);
int main(void)
{
int i = 0;
int choice = 0;
char name[STR_LEN] = { 0 };
int age = 0;
char friends[3][STR_LEN];
personNode* head = (personNode*)malloc(sizeof(personNode));
head->next = NULL;
while (choice != 7)
{
printf("\n\nWelcome to MagshiParty Line Management Software!\nPlease enter your choice from the following options :\n1 - Print line\n2 - Add person to line\n3 - Remove person from line\n4 - VIP guest\n5 - Search in line\n6 - Reverse line\n7 - Exit\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
{
printf("%d people in line: \n", recursiveLength(head, 0));
recursivePrint(head);
break;
}
case 2:
{
printf("Welcome guest!");
printf("\nEnter name: ");
getchar();
scanf("%[^\t\n]s", name);
getchar();
printf("\nEnter age: ");
scanf("%d", &age);
printf("Enter names of 3 friends: ");
for (i = 0; i < 3; i++)
{
printf("\nFriend %d: ", i + 1);
getchar();
scanf("%[^\t\n]s", friends[i]);
getchar();
}
createPerson(name, age, friends, head);
break;
}
case 3:
{
printf("Enter name to remove: ");
getchar();
scanf("%[^\t\n]s", name);
getchar();
removePersonByName(name, head);
break;
}
case 4:
{
printf("VIP GUEST!\n");
printf("Enter name: ");
getchar();
scanf("%[^\t\n]s", name);
getchar();
printf("Enter age: ");
scanf("%d", &age);
personNode* newNode = (personNode*)malloc(sizeof(personNode));
newNode->age = age;
strcpy(newNode->name, name);
newNode->next = NULL;
addToListTop(newNode, head);
break;
}
case 5:
{
printf("Enter name to search: ");
getchar();
scanf("%[^t\n]s", name);
getchar();
search(head, name);
break;
}
case 6:
{
head = reverseList(head);
break;
}
case 7:
{
freeList(head);
printf("Goodbye!");
break;
}
default:
{
freeList(head);
printf("Goodbye!");
break;
}
}
}
getchar();
getchar();
return 0;
}
int recursiveLength(personNode* head, int counter)
{
personNode* curr = head;
if (head->next == NULL)
{
return counter;
}
else
{
if (curr->next != NULL)
{
counter++;
recursiveLength(curr->next, counter);
}
else
{
return counter;
}
}
}
int recursivePrint(personNode* head)
{
personNode* curr = head;
if (head->next == NULL)
{
return 0;
}
else
{
if (curr->next != NULL)
{
printf("Name: %s, Age: %d \n", curr->name, curr->age);
recursivePrint(curr->next);
}
else
{
return 0;
}
}
}
void createPerson(char name[], int age, char friends[3][STR_LEN], personNode* head)
{
int i = 0;
personNode* newNode = (personNode*)malloc(sizeof(personNode));
for (i = 0; i < 3; i++)
{
strcpy((newNode->friends[i]), friends[i]);
//printf("inserted = %s , bimkom - %s\n", (newNode->friends[i]), friends[i]);
}
newNode->age = age;
strcpy(newNode->name, name);
newNode->next = NULL;
link(head, newNode);
}
void link(personNode* head, personNode* toLink)
{
personNode* curr = head;
int i = 0;
if (head->next == NULL) // first node - list empty
{
//printf("First!");
for (i = 0; i < 3; i++)
{
strcpy((head->friends[i]), (toLink->friends[i]));
//printf("inserted = %s , bimkom - %s\n", (head->friends[i]), toLink->friends[i]);
}
//curr->next = malloc(sizeof(personNode));
curr->age = toLink->age;
strcpy(curr->name, toLink->name);
head->next = toLink;
//curr->next = NULL;
}
else
{
char foundFriend[STR_LEN] = { 0 };
strcpy(foundFriend, iHaveFriends(toLink, head));
//printf("returned from iHaveFriends: %s", foundFriend);
if (!addBehindFriend(foundFriend, toLink, head))
{
//printf("addBehindFriend Failed!");
while (curr->next != NULL)
{
curr = curr->next;
}
//curr->next = malloc(sizeof(personNode));
for (i = 0; i < 3; i++)
{
*(head->friends[i]) = toLink->friends[i];
}
curr->age = toLink->age;
strcpy(curr->name, toLink->name);
curr->next = toLink;
}
}
}
char* iHaveFriends(personNode* guest, personNode* head)
{
personNode* curr = head;
int i = 0;
char foundFriend[STR_LEN] = { 0 };
while (curr->next != NULL)
{
for (i = 0; i < 3; i++)
{
if (strcmp(curr->name, guest->friends[i]) == 0)
{
//printf("\nMATCH: %s, %s, %s\n", foundFriend, guest->friends[i], curr->name);
strcpy(foundFriend, guest->friends[i]);
}
else
{
//printf("\nProblem in friend Check!, compared: %s, %s\n", curr->name, guest->friends[i]);
}
}
//printf("\nName: %s", curr->name);
curr = curr->next;
}
//printf("\nReturning: %s", foundFriend);
return foundFriend;
}
int addBehindFriend(char* friendName, personNode* guest, personNode* head)
{
//printf("\nrecived: %s, %s\n", friendName, guest->name);
personNode* curr = head;
personNode* temp = 0;
char foundFriend[STR_LEN] = { 0 };
int flag = 0;
while (curr->next != NULL)
{
if (strcmp(friendName, curr->next->name) == 0)
{
flag = 1;
temp = curr->next;
curr->next = guest;
guest->next = temp;
}
else
{
//printf("%s, %s\n", friendName, curr->next->name);
}
curr = curr->next;
}
return flag;
}
void removePersonByName(char name[], personNode* head)
{
personNode* curr = head;
int flag = 0;
while (curr->next != NULL)
{
if (strcmp(curr->next->name, name) == 0 && curr->next->next != NULL)
{
flag = 1;
curr->next = curr->next->next;
break;
}
curr = curr->next;
}
if (flag)
{
printf("%s removed from line", name);
}
else
{
printf("%s not in line", name);
}
}
void addToListTop(personNode* VIP, personNode* head)
{
personNode* tmp = (personNode*)(malloc(sizeof(personNode)));
tmp->age = head->age;
strcpy(tmp->name, head->name);
tmp->next = head->next;
head->age = VIP->age;
strcpy(head->name, VIP->name);
head->next = tmp;
//VIP->next = tmp;
}
void search(personNode* head, char name[])
{
personNode* curr = head;
int flag = 0;
while (curr->next != NULL)
{
if (strcmp(curr->name, name) == 0)
{
flag = 1;
break;
}
curr = curr->next;
}
if (flag)
{
printf("%s found in line", name);
}
else
{
printf("%s not in line", name);
}
}
personNode* reverseList(personNode* head)
{
personNode* curr = head;
personNode* previous = NULL;
personNode* next = NULL;
while (curr != NULL)
{
next = curr->next;
curr->next = previous;
previous = curr;
curr = next;
}
head = previous;
printf("Line reversed!");
return head;
}
Your reverse function logic seems fine. There's a problem in your recursiveprint function, so here you go, try this simple one:
void print(struct personNode *head)
{
struct personNode *temp = head;
while(temp != NULL)
{
printf("%s ", temp->name);
temp = temp->next;
}
}
The Reverse function was not working as it should on my local machine.
It was hard to debug it so I prefered to rewrite it.
Reverse function works like this :
static personNode * reverse(struct personNode *head)
{
struct personNode* localHead = NULL;
struct personNode* temp;
struct personNode* remainingHead;
while (head != NULL)
{
remainingHead = head->next;
temp = localHead;
localHead = head;
localHead->next = temp;
head = remainingHead;
}
return localHead;
}
Regarding youre recursive print function
I am checking the head for null , not the next pointer.
int recursivePrint(personNode* head)
{
personNode* curr = head;
if (head == NULL)
{
return 0;
}
else
{
if (curr != NULL)
{
printf("Name: %s, Age: %d \n", curr->name, curr->age);
recursivePrint(curr->next);
}
else
{
return 0;
}
}
}
#include <stdio.h>
#include <stdlib.h>
struct treeNode
{
char *word;
int NumberCnt;
struct treeNode *rightPTR, *leftPTR;
};
typedef struct treeNode node;
node *rootPTR = NULL;
void freeTree(node *currPTR)
{
if (currPTR!= NULL)
{
freeTree(currPTR -> leftPTR);
free(currPTR);
freeTree(currPTR -> rightPTR);
}
}
void printTree(node *currPTR)
{
if (currPTR != NULL)
{
printTree(currPTR ->leftPTR);
printf("%s appeared:%d times\n", currPTR->word, currPTR->NumberCnt);
printTree(currPTR ->rightPTR);
}
}
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = input;
tempPTR -> NumberCnt=0;
tempPTR -> leftPTR = NULL;
tempPTR -> rightPTR = NULL;
if (rootPTR == NULL)
{
rootPTR = tempPTR;
rootPTR -> NumberCnt++;
}
else
{
node *currPTR = rootPTR;
node *prevPTR = NULL;
while (currPTR != NULL)
{
int comp = strcmp(input, (currPTR->word));
if (comp == 0)
{
printf ("Entry already exists\n");
currPTR->NumberCnt++;
return 1;
}
else if (comp < 0)
{
prevPTR = currPTR;
currPTR = currPTR->leftPTR;
}
else if (comp > 0)
{
prevPTR = currPTR;
currPTR = currPTR->rightPTR;
}
}
int comp = strcmp(input, (prevPTR ->word));
if (comp < 0)
{
prevPTR->leftPTR = tempPTR;
prevPTR ->NumberCnt++;
}
else if (comp > 0)
{
prevPTR->rightPTR = tempPTR;
prevPTR->NumberCnt++;
}
return 0;
}
printf("root1%s\n",rootPTR->word);
return 2;
}
int search(char* input)
{
if (input == rootPTR ->word)
{
printf("Node found %s\n", rootPTR->word);
return 0;
}
else
{
if (input < rootPTR ->word)
{
node *currPTR = rootPTR->leftPTR;
while (currPTR != NULL)
{
if (input == currPTR->word)
{
printf("Node found %s\n", currPTR->word);
return 0;
}
else if (input < currPTR->word)
{
currPTR = (currPTR -> leftPTR);
}
else if (input > currPTR->word)
{
currPTR = (currPTR -> rightPTR);
}
}
printf ("Node not in tree\n");
return 1;
}
if (input > rootPTR ->word)
{
node *currPTR = rootPTR->rightPTR;
while (currPTR != NULL)
{
if (input == currPTR->word)
{
printf ("Node found %s\n", currPTR->word);
return 0;
}
else if (input < currPTR->word)
{
currPTR = (currPTR -> leftPTR);
}
else if (input > currPTR->word)
{
currPTR = (currPTR ->rightPTR);
}
}
printf ("Node not in tree\n");
return 1;
}
}
return 2;
}
void fixWord(char* buff)
{
char* unfixed = buff;
char* fixed = buff;
while (*unfixed)
{
if (isalpha(*unfixed))
{
*fixed=tolower(*unfixed);
*fixed++;
}
*unfixed++;
}
*fixed=0;
}
int main()
{
FILE *ptr_file;
char buff [100];
//ptr_file = fopen ("sherlock.txt", "r");
ptr_file = fopen ("input.txt", "r");
if (!ptr_file)
printf("File read error");
while(fscanf(ptr_file, "%s ", buff ) != EOF)
{
int comparison = strcmp(buff, "endoffile");
if (comparison == 0)
{
return 0;
}
fixWord(buff);
insertNode(buff);
}
fclose(ptr_file);
printf("root:%s\n", rootPTR->word);
return 0;
}
Ok I have this binary tree which is taking string inputs from a file. It works if I pass strings directly to the tree, however when I attempt to pass it the strings I read in form the file it keeps on replacing the root node and does not add them correctly to the tree.
buff is current line value and overwritten on each line reading:
insertNode(buff);
insertNode assigns overwriten buffer.
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = input;
....
So, you should dynamic allocation for input value as:
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = strdup(input);
....
You're passing buff to your insert function, and it's storing that in the node. So all your nodes will end up pointing to the same address, that of buff in main.
You need to allocate storage for each string in each node, and copy your input into that. And remember to deallocate properly when you delete your tree.
strdup can be handy for that if your library has it.