Linked lists - deleting a list
I have a program that takes two arguments and makes a random word., The first argument argv[1] is the number of letters in the word, and the second argument is the random number seed.
I need to put each random character into a node in a linked list and after I've done that, I need to print out the linked list (the random word). FInally, I need to be able to delete any characters that are duplicated in a row and then print out the new word.
This is what I have:
Code:
#include <stdio.h>
#include <stdlib.h>
#define ALPHABET 26
typedef struct _Node {
char letter;
struct _Node *next;
} NodeT;
int isNum(char *);
NodeT *addNode(NodeT *);
NodeT *addLetter(NodeT *);
void printList(NodeT *);
NodeT *removeDupes(NodeT *);
int main(int argc, char **argv) {
int length = 0;
int seed = 0;
NodeT *head1 = NULL;
NodeT *head2 = NULL;
int i = 0;
if (argc != 3 || !isNum(argv[1]) || !isNum(argv[2])) {
fprintf(stderr, "Usage: ./llrandword "
"wordlength randomseed\n");
return EXIT_FAILURE;
}
length = atoi(argv[1]);
seed = atoi(argv[2]);
srandom(seed);
for(i=0; i<length; i++) {
head1 = addNode(head1);
}
head1 = addLetter(head1);
printList(head1);
putchar('\n');
head2 = head1;
head2 = removeDupes(head1);
printList(head2);
putchar('\n');
return EXIT_SUCCESS;
}
int isNum(char *string) {
int isNum = 1;
while(*string != '\0') {
if (*string < '0' || *string > '9') {
isNum = 0;
}
string++;
}
return isNum;
}
NodeT *addNode(NodeT *list) {
NodeT *new = NULL;
NodeT *cur = NULL;
new = malloc(sizeof(NodeT));
if (new == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
if (list == NULL) {
list = new;
} else {
cur = list;
while (cur->next != NULL) {
cur=cur->next;
}
cur->next = new;
}
new->next = NULL;
return list;
}
NodeT *addLetter(NodeT *head) {
NodeT *cur = NULL;
int r = 0;
int rand = 0;
for(cur = head; cur != NULL; cur = cur->next) {
r = random();
rand = r % ALPHABET;
cur->letter = 'a'+rand;
}
return head;
}
void printList(NodeT *head) {
NodeT *cur = NULL;
for (cur=head; cur != NULL; cur=cur->next) {
printf("%c", cur->letter);
if(cur->next != NULL) {
printf("->");
}
}
}
NodeT *removeDupes(NodeT *head) {
NodeT *cur = NULL;
NodeT *tmp = NULL;
for(cur=head; cur->next != NULL; cur = cur->next) {
if (cur->letter == cur->next->letter) {
tmp->next = cur->next->next;
cur->next->next = NULL;
free(cur->next);
cur->next = tmp->next;
tmp->next = NULL;
}
}
return head;
}
When I execute the program, this is what I get:
Quote:
$ ./llrandword 10 1
n->w->l->r->b->b->m->q->b->h
Segmentation fault (core dumped)
What the output should be is
Quote:
$ ./llrandword 10 1
n->w->l->r->b->b->m->q->b->h
n->w->l->r->b->m->q->b->h
I have a feeling something is wrong with the removeDupes function.