c - printing linked list from beginning -
I got the code from Wikipedia for the linked list ().
But it prints the result in reverse order (5 4 3 2 1). How to print it from the beginning (1 2 3 4 5)
Given the following example:
/ **** ************************************************************************** ************** ********** / * * Function: Add an element to our list * / / * * / / * parameter: ** p he The node on which we want to insert. * / / * If the node is initially empty it / / * other wise it is put in the next location * / list * list_add (list ** p, int i) {if (p == NULL) / * see it Checks whether the indicators return somewhere in the space / refund; LLIST * n = Molok (sizeoff (LIIST)); / * Creates new node of correct data size * / if (n == NULL) return tap; N- & gt; Next = * p; / * The last element (* p) now becomes the "Next" element * / * p = n; / * Add new empty element to the front of the list * / n- & gt; Data = i; Return * p; }
When you call list_add
, adding elements to beginning of the linked list. This is for reasons of efficiency; You do not have to change the entire link list to include an element (which you have to do if you want to).
To print in reverse, you can use recycling, create your own stack (the blind man is recursive), or re-create the list in reverse. A recurring version:
zero list_rate_array (list * n) {if (n == NULL) {printf ("list is empty \ n"); Return; } If (n-> Next! = Null) {list_print_reverse (n-> gt; Next); } Printf ("print% p% p% d \ n", n, n- & gt; next, n- & gt; data); }
Comments
Post a Comment