Hi,
I've been trying to solve problem Plug-in, and I used linked lists to do so. I managed to solve it for most test examples that I came up with, but on one particular test example I get Runtime error.
Can you please tell me what might be the problem?
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#define WORD_MAX 200010
typedef struct node_
{
char letter;
struct node_ *next;
} node;
void add_to_end(node** start, node** end, char c)
{
node* new = malloc(sizeof(node));
new->next = NULL;
new->letter = c;
if (*start == NULL)
{
*start = new;
*end = new;
return;
}
(*end)->next = new;
*end = new;
}
int remove_same(node** start)
{
node* temp = *start, *temp_2;
if (temp == NULL || temp->next == NULL)
return 0;
if (temp->letter == temp->next->letter)
{
*start = temp->next->next;
return 1;
}
while (temp != NULL && temp->next != NULL)
{
if (temp->next->next == NULL)
return 0;
if (temp->next->letter == temp->next->next->letter)
{
temp_2 = temp->next->next->next;
free(temp->next);
free(temp->next->next);
temp->next = temp_2;
return 1;
}
temp = temp->next;
}
return 0;
}
int main()
{
char word[WORD_MAX];
gets(word);
unsigned i;
node* list_start = NULL, *list_end = NULL;
for(i=0; word[i]; i++)
add_to_end(&list_start, &list_end, word[i]);
while(remove_same(&list_start))
;
if (list_start == NULL)
return 0;
while(list_start)
{
putchar(list_start->letter);
list_start=list_start->next;
}
return 0;
}









Dynamic memory is very delicate. If you must use linked lists, you should always try to do it with arrays instead of pointers. You can have a Next[] and Prev[] arrays to simulate the behaviour of the pointers.
Check out my submission for that problem -> 3619072
Anyway, this problem does not require linked lists. You could solve it just by doing something like this -> 3619085
Hm,
I actually saw that I could solve this problem during loading data, but it was more challanging to solve it using linked lists. Do you see any probable cause gor this kind of mistake?
You say why you're getting runtime error or why you decided to go the hard way and do a linked list with pointers?
If you're talking about the runtime error, then I'd have to debug your code, but you'll surely accessing an element of a null pointer somewhere in the code.