I've always set my struct definitions to something along the lines of
Code:
typedef struct node {
char *text;
struct node *next;
} Line;
But now I want to also add a previous pointer so that I can traverse the link not only forwards, but backwards:
Code:
typedef struct node {
char *text;
struct node *next;
struct node *prev;
} Line;
The code I have for typical forward traversals works fine, but my new code is now:
Code:
Line *makeNode(char *text) {
Line *new = NULL;
new = malloc(sizeof(Line));
if (new == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
new->text = strdup(text);
new->next = NULL;
new->prev = NULL;
return new;
}
Line *joinList(Line *head1, Line *head2) {
Line *cur = head1; //Line *cur = NULL; cur = head1;
if (cur == NULL) {
head1 = head2;
} else {
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = head2;
head2->prev = cur;
}
return head1;
}
and when I test it with
Code:
for (cur = head; cur != NULL; cur = cur->next) {
printf("%s", cur->text);
}
cur = cur->prev;
while (cur != NULL) {
printf("%s", cur->text);
cur = cur->prev;
}
It prints out the list in the forward direction, but seg faults on the way back. What am I doing wrong?