Hello everyone,
I have a program that intends to create a doubly linked list of structures, using the following header (q1.h):
typedef struct lNode* ListNodePtr;
typedef struct lNode {
char* string;
ListNodePtr next;
ListNodePtr prev;
} ListNode;
This is my implementation:
#include "q1.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
ListNodePtr tail = 0;
ListNodePtr newNode(void);
ListNodePtr addNode(ListNodePtr h, char *w);
void printList(ListNodePtr h);
void deleteNode(ListNodePtr h, char *w);
ListNodePtr newNode(void)
{
ListNodePtr n;
n = (ListNodePtr)malloc(sizeof(ListNode));
n->prev = 0;
n->next = 0;
return n;
}
ListNodePtr addNode(ListNodePtr h, char *w)
{
ListNodePtr a;
if (h == 0 && tail == 0)
{
a = newNode();
h = a;
h->string = w;
h->next = tail;
tail = a;
tail->prev = h;
}
else
{
a = newNode();
a->prev = tail;
tail->next = a;
a->next = 0;
tail = a;
tail->string = w;
}
return h;
}
void printList(ListNodePtr h)
{
if (h == NULL)
printf("List is empty\n");
else
{
while (h != 0)
{
printf("%s\n", h->string);
h = h->next;
}
}
}
void deleteNode(ListNodePtr h, char *w)
{
ListNodePtr temp;
temp = h;
if (h == 0)
printf("List is empty\n");
else
{
while (temp != 0)
{
if (temp->string == w)
{
if (temp == h) //if node is first
{
h = h->next;
h->prev = 0;
}
else
{
if (temp->next == 0) //if node is last
temp->prev->next = 0;
else
{
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
}
free(temp);
}
}
temp = temp->next;
}
}
}
int main(void)
{
char s[50] = "";
char command[10];
char word[50];
int scanfReturnValue;
ListNodePtr head = 0;
while ((fgets(s,50,stdin)) != 0)
{
scanfReturnValue = sscanf(s, "%s %s", command, word);
if (scanfReturnValue == 2)
{
if (strcmp(command, "insert") == 0)
{
head = addNode(head, word);
}
else if (strcmp(command, "delete") == 0)
deleteNode(head, word);
}
else if (scanfReturnValue == 1)
{
if (strcmp(command, "print") == 0)
printList(head);
}
}
return 0;
}
My addNode method is supposed to add nodes to the end of the list, which it does, but it seems to change the enclosed string in each node to the last value added.
For example, here is a sample run:
insert 1
1
insert 2
2
2
insert 3
3
3
3
I have tested some of the values in the list, and have verified that any time we add more than one value in it, it will change the head's string to the last string entered.
Also, the deleteNode method will always give a segmentation fault when attempting to remove a node with a particular string:
insert 1
1
delete 1
Segmentation fault
Thanks in advance for any help that can be offered