• 06-02-2004
dionys
Hi Guys.I have some questions for this program.
This program uses linked lists to construct a stack (lifo)
I dont understand the bold part of the code:
In general i dont understand why
Pop() and Push() use a double pointer .... :confused:
Code:

```* lifo-list.c */ #include <stdio.h> #include <stdlib.h> struct node {         int data;         struct node *next; };```
Code:

```void Push(struct node **headRef, int newData) {         struct node *newNode = (struct node*)malloc(sizeof(struct node));   newNode->data = newData;         newNode->next = (*headRef);           (*headRef) = newNode;         return; }```
Code:

```int Pop(struct node **headRef) {         struct node *head;         int result;           head = *headRef;         if(head != NULL) {                 result = head->data;                 *headRef = head->next;                 free(head);                 return(result);         } else {                 printf("Pop() - Underflow !!\n");                 return(0);         } }```
Code:

```int Length(struct node *head) {         int count = 0;         struct node* current = head;           while(current != NULL) {                 count++;                 current = current->next;         }         return(count); }```
Code:

```int main() {         struct node *stack = NULL;         int x, i, n;         printf("\n Enter sequence of integers (EOF to stop): ");         while(scanf("%d", &x) == 1) {                 printf("  %d values\n",&stack);                 Push(&stack, x);         }         n = Length(stack);         printf("\t Stack contains %d values\n", n);         printf("\n Stack values (in reverse order) :\n");         for(i = 0; i < n; i++) {                 printf("\t value #%d: [%d]\n", i, Pop(&stack));         } printf("\n Calling Pop() with empty stack: value=%d\n", Pop(&stack));         return(0); }```
• 06-02-2004
quzah
They're being passed a pointer to the list itself, so they can update the head of the list. Remember, any time you want to change something in a function, you need a pointer to it. Thus, if you want to change the pointer that stored your list, you need a pointer to that list so it can be changed inside the function call itself. (You can of course do it this way...)
Code:

```Node *popanddestroy( Node *list ) {     Node *n;     n = list->next; /* point to the top->next node so we can keep track of it */     free( list ); /* free the top node */     return n; /* return the new "top" */ } ... Node *list = constructabiglistfunction( ); ... list = popanddestroy( list ); /* get rid of the top one, assign the list the next one */```
This would inside the function, strip the top node of the list. It then returns the "next" one, which is assigned via a return value to the "list" pointer.

Or, by using a pointer to a pointer, you do it in one shot:
Code:

```Node *list = makeabiglist( ); pop( &list ); /* strips the top one off, does something to it, updates the list itself */```
Quzah.