Ok, so i have a link list of structs.. but in the wrong direction, is there a way to flip the elements in the link list?
for example
if have pointer -> 1-> 2 -> 3 ->Null
but i need it pointer ->3 -> 2 -> 1 -> Null
sorry if this seems confusing
Ok, so i have a link list of structs.. but in the wrong direction, is there a way to flip the elements in the link list?
for example
if have pointer -> 1-> 2 -> 3 ->Null
but i need it pointer ->3 -> 2 -> 1 -> Null
sorry if this seems confusing
How about: for each node in the linked list (excluding the first node), set next equal to the previous node in the list. For a doubly linked list, this wouldn't be necessary.
Just do some pointer surgery. Make a new, reversed list by stepping through your old list and attaching nodes after the head node of the new list.
Code:struct ll { int k; ll * next; }; struct ll * insert_after ( struct ll * beforenode, struct ll * datanode ) { struct ll * rv = NULL; if ( datanode != NULL ) { if ( beforenode != NULL ) { beforenode->next = datanode; } rv = beforenode == NULL ? datanode : beforenode; } return rv; } struct ll * reverse ( struct ll * headnode ) { struct ll * reverselist = NULL; while( headnode != NULL ) { reverselist = insert_after( reverselist, headnode ); headnode = headnode->next; } return reverselist; }
Last edited by whiteflags; 04-17-2008 at 06:36 PM.
Awesome, thanks guy i got it but i have another simple question, how would i pass a pointer(to a struct) to a function??
ThanksCode:struct node { double coefficient; int power; struct node *next; }; main() { struct node *first; ....code(first will be link) add( ??? ); ....code } add( ??? ) { }
-dyn4sty
The same way you pass any other variable: by putting its name inside the (parentheses) right after the function name.
And of course, you have to put the type in the function declaration: struct node *.
ahh, got it, i'm new to C and still confused on where i should and shouldnt put *'s and &'s. thanks everyone for the help
-Dyn4sty