Question

I am writing a program that converts strings to linked lists, and alters them, in C.

For some reason after I call my reverse function, and then print the list, it will print a new line before printing the reversed list.

for example, say my 'list' contains... a->p->p->l->e->NULL

in main() if i call... print(list); print(list);

my output:

apple
apple

BUT, in main() if i call... print(list); list=reverse(list); print(list);

my output:

apple 
/*empty line*/ 
elppa

here is my rev()

node *rev(node *head){

    node *r_head = NULL;
    while (head) {
        node *next = head->next;
        head->next = rev_head;
        r_head = head;
        head = next;
    }

    return r_head;
}
Was it helpful?

Solution

It seems like you're reversing the list a little too well; the NULL at the end of your list is becoming the new head, which is creating that empty space you were concerned about.

To fix it, I would suggest checking if head->next is NULL inside your while loop:

node *rev(node *head){

    node *r_head = NULL;
    while (head->next) {
        node *next = head->next;
        head->next = rev_head;
        r_head = head;
        head = next;
    }
    r_head = head;

    return r_head;
}

This code has not been tested, but I believe it should work.

OTHER TIPS

If you have a carriage return in your string right before your NULL character, it will take the place of the first character, hence starting the second string with an additional return.

As a suggestion, take your carriage return outside of the string.

Although your question left out all the details, my ESP tells me that you used some variant of gets for your input function, which also captures the newline:

gets() ==> "A P P L E [newline]"

Then when you reversed it, you ended up with

"[newline] E L P P A"

And when you printed out the original string and new string back to back, you got:

"A P P L E [NL] [NL] E L P P A"

And, if you had attached a debugger and stepped through your code, like all developers should, you would already have the answer!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top