Thread: How to show the list number

  1. #1
    Registered User
    Join Date
    Nov 2019
    Posts
    90

    How to show the list number

    I am trying to write code that show the list of two nods

    I have written following code and I want help to show the list numbers.

    Code:
     #include<stdio.h>
    
    struct list
    {
    	int n;
    	struct list *next;
    }
    
    
    void main()
    {
    	/* Both first and last are null pointer */
    	struct list *first = NULL;
    	struct list *last = NULL;
    	
    	/* Allocate dyanamic memory */
    	first = malloc(sizeof(*first));
    	last = malloc(sizeof(*last));
    	
    	first->n = 5;  /* first pointer point data of first node*/ 
    	first-> next = last; /* first pointer point address of next node*/ 
    	
    	last->n = 10;  /* last pointer point data of last node*/ 
    	last->next = NULL; /*last pointer set as NULL pointer because there is no next node */
    		
    }
    How to show the list numbers ?
    Code:
    #include<stdio.h>
    Code:
    struct list
    {
    	int n;
    	struct list *next;
    }
    
    
    void main()
    {
    	/* Both first and last are null pointer */
    	struct list *first = NULL;
    	struct list *last = NULL;
    
    	/* Allocate dyanamic memory */
    	first = malloc(sizeof(*first));
    	last = malloc(sizeof(*last));
    
    	first->n = 5;  /* first pointer point data of first node*/ 
    	first-> next = last; /* first pointer point address of next node*/ 
    
    	last->n = 10;  /* last pointer point data of last node*/ 
    	last->next = NULL; /*last pointer set as NULL pointer because there is no next node */
    
    }

  2. #2
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,791
    Ok, for a start that code shouldn't even compile (apart from not including stdlib.h it still shouldn't compile). Second, it's not a typical way to construct a linked list, but I'll assume you've written it that way just as a test.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    struct list
    {
        int n;
        struct list *next;
    };
     
     
    int main(void)
    {
        /* Both first and last are null pointer */
        struct list *first = NULL;
        struct list *last = NULL;
         
        /* Allocate dyanamic memory */
        first = malloc(sizeof(*first));
        last = malloc(sizeof(*last));
         
        first->n = 5;  /* first pointer point data of first node*/
        first-> next = last; /* first pointer point address of next node*/
         
        last->n = 10;  /* last pointer point data of last node*/
        last->next = NULL; /*last pointer set as NULL pointer because there is no next node */
    
        /* Traverse the list (i.e. from the head until NULL is encountered) printing the value of n from
            the current node (curr) 
         */
        struct list *curr;  /* Shouldn't this be better named? E.g. struct node */
        for (curr = first; curr != NULL; curr = curr->next) {
            printf("%d\n", curr->n);
        }
        
        return 0;
    }
    Printing the list should be a function rather than how I've written it here though

    * I haven't compiled the code so don't blame me if it doesn't work

    My suggestions are:
    a) change the name of that struct from 'list' to 'node' because that's what it is (make another struct for list if that's the approach you decide to take... it's not the only way to do it)
    b) write a function that adds a node to the tail of the list
    c) write a function to print the list
    d) free the memory you've allocated (writing a function called something like destroy_list is probably the easiest way; the loop will be similar to the print loop)
    Last edited by Hodor; 12-29-2019 at 10:15 PM.

  3. #3
    Registered User
    Join Date
    Nov 2019
    Posts
    90
    Quote Originally Posted by Hodor View Post

    My suggestions are:
    a) change the name of that struct from 'list' to 'node' because that's what it is (make another struct for list if that's the approach you decide to take... it's not the only way to do it)

    c) write a function to print the list
    Ok I have written function to print the list

    Code:
    #include<stdio.h>
    
    #include<stdlib.h>
     
    struct node
    {
        int n;
        struct node *next;
    };
      
    void show(struct node *current, struct node *first ){
         
         for (current = first; current != NULL; current = current->next) {
            printf("%d\n", current->n);
        
         }
    }  
    void main(void)
    {
        /* Both first and last are null pointer */
        struct node *first = NULL;
        struct node *last = NULL;
        struct node *current = NULL;
          
        /* Allocate dyanamic memory */
        first = malloc(sizeof(*first));
        last = malloc(sizeof(*last));
          
        first->n = 5;  /* first pointer point data of first node*/
        first-> next = last; /* first pointer point address of next node*/
          
        last->n = 10;  /* last pointer point data of last node*/
        last->next = NULL; /*last pointer set as NULL pointer because there is no next node */
     
        /* Traverse the list (i.e. from the head until NULL is encountered) printing the value of n from
            the current node (curr) 
         */
       
         show (current, first);
    }
    Last edited by Player777; 12-29-2019 at 11:05 PM.

  4. #4
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,791
    That's looking better You don't need to pass current to the function... just have it as a local variable. Something like

    Code:
    void show(struct node *first ){
         struct node *current; 
         for (current = first; current != NULL; current = current->next) {
            printf("%d\n", current->n);
         
         }
    }
    and in main

    Code:
    show (first);


    Whole program (not compiled or tested)
    Code:
    #include<stdio.h>
    #include<stdlib.h>
      
    struct node
    {
        int n;
        struct node *next;
    };
       
    void show(struct node *first ){
         struct node *current; 
         for (current = first; current != NULL; current = current->next) {
            printf("%d\n", current->n);
         
         }
    }  
    
    int main(void)
    {
        /* Both first and last are null pointer */
        struct node *first = NULL;
        struct node *last = NULL;
           
    
        /* Allocate dyanamic memory */
        first = malloc(sizeof(*first));
        last = malloc(sizeof(*last));
           
        first->n = 5;  /* first pointer point data of first node*/
        first-> next = last; /* first pointer point address of next node*/
           
        last->n = 10;  /* last pointer point data of last node*/
        last->next = NULL; /*last pointer set as NULL pointer because there is no next node */
      
        /* Traverse the list (i.e. from the head until NULL is encountered) printing the value of n from
            the current node (curr) 
         */
        
         show (first);
    
        /* Strictly speaking this return 0 is not required because the C
         * standard says that reaching the closing brace (}) of main, but
         * not other functions, is equivalent to returning 0. But main
         * should return an int (not void)
         */
         return 0;
    }

    Should do the trick

  5. #5
    Registered User
    Join Date
    Nov 2019
    Posts
    90
    Quote Originally Posted by Hodor View Post
    b) write a function that adds a node to the tail of the list
    I found this Linked list - Wikipedia

    I have to write something like this


    Code:
    nodeaddNode(nodehead,intvalue){   node temp, p; // declare two nodes temp and p
       temp = createNode(); // assume createNode creates a new node with data = 0 and next pointing to NULL.
       temp->data = value; // add element's value to data part of node
       if (head == NULL) {
           head = temp;     // when linked list is empty
       }
       else {
           p = head; // assign head to p 
           while (p->next != NULL) {
               p = p->next; // traverse the list until p is the last node. The last node always points to NULL.
           }
           p->next = temp; // Point the previous last node to the new node created.
       }
       return head;
     }
    What do these temp and p pointer do in function ?

  6. #6
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,791
    Quote Originally Posted by Player777 View Post
    I found this Linked list - Wikipedia

    I have to write something like this


    Code:
    nodeaddNode(nodehead,intvalue){   node temp, p; // declare two nodes temp and p
       temp = createNode(); // assume createNode creates a new node with data = 0 and next pointing to NULL.
       temp->data = value; // add element's value to data part of node
       if (head == NULL) {
           head = temp;     // when linked list is empty
       }
       else {
           p = head; // assign head to p 
           while (p->next != NULL) {
               p = p->next; // traverse the list until p is the last node. The last node always points to NULL.
           }
           p->next = temp; // Point the previous last node to the new node created.
       }
       return head;
     }
    What do these temp and p pointer do in function ?
    Personally I think that a better name for 'temp' would be 'newnode' (because it's the new node, it's just not inserted onto the list yet). 'p' is essentially what's called 'current' in your show() code... it's just used to find the last node in the list. Once the last node in the list -- usually referred to as the tail -- is found then 'temp' (or as I suggest, 'newnode') is added to the list at that position

    Code:
           p = head; // assign head to p 
           while (p->next != NULL) {
               p = p->next; // traverse the list until p is the last node. The last node always points to NULL.
           }
    is just another way to write the for loop used in show(). It's the same as (using the name 'first' so it matches your code instead of 'head' as in the Wikipedia example)

    Code:
    for (p = first; p != NULL; p = p->next)
        ; /* Nothing to do here in the body of the loop, we just want to find the tail of the linked list */
    I wouldn't bother too much about 'for' vs 'while'. They're doing the same thing in this case: traversing the list until the the end is reached.

  7. #7
    Registered User
    Join Date
    Nov 2019
    Posts
    90
    Quote Originally Posted by Hodor View Post
    b) write a function that adds a node to the tail of the list
    i don't get more help with this function

    Code:
    nodeaddNode(nodehead,intvalue){   node temp, p; // declare two nodes temp and p
       temp = createNode(); // assume createNode creates a new node with data = 0 and next pointing to NULL.
       temp->data = value; // add element's value to data part of node
       if (head == NULL) {
           head = temp;     // when linked list is empty
       }
       else {
           p = head; // assign head to p 
           while (p->next != NULL) {
               p = p->next; // traverse the list until p is the last node. The last node always points to NULL.
           }
           p->next = temp; // Point the previous last node to the new node created.
       }
       return head;
     }
    could you tell me please, How can I use this function or better way in my code to adds a node to the tail of the list

  8. #8
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,791
    Normally you'd (probably[1]) use a pointer to a pointer (**) in the function, something like:

    Code:
    struct node *addNode(struct Node **head, int value) {}
    because you have to be able to change what head points to in the case of an empty list; i.e. in an empty list head is pointing to NULL so you need to be able to update what head points to in that situation. Another way is to use a struct. Maybe you're just having trouble understanding the Wikipedia example because the example there is using names that don't match up with your current code (or my thinking for that matter.... their use of 'temp' is weird because it's in no way temporary it just hasn't been added to the list yet). I'll use a struct so that you don't have to worry about pointers to pointers for now. Anyway since the Wikipedia example might be confusing I've written the exact same code using variable names closer to what you've used

    Code:
    #include<stdio.h>
    #include<stdlib.h>
      
    struct node
    {
        int n;
        struct node *next;
    };
    
    struct list
    {
        struct node *head;  /* AKA 'first' */
    };
       
    void show(const struct list *mylist)
    {
         struct node *current; 
    
         for (current = mylist->head; current != NULL; current = current->next) {
            printf("%d\n", current->n);
         
         }
    }
    
    /* This function is identical to the Wikipedia pseudocode you provided
     */
    struct node *addNode(struct list *mylist, int value)
    {
        struct node *newnode;
        
        newnode = malloc(sizeof *newnode);
        /* Should add error checking here to ensure malloc() succeeded */
        newnode->next = NULL;
        newnode->n = value;
        
        if (mylist->head == NULL) { /* If list is empty then add at head */
            mylist->head = newnode;
        } else { /* otherwise find the tail (last node) of the list and add there */
            /* find the tail, AKA 'last' */
            struct node *p = mylist->head;
            while (p->next != NULL) {
                p = p->next;
            }
            /* p now points to the tail of the list. Add our new node here.  p->next is currently NULL so change it to point to our new node */
            p->next = newnode;
        }
        
        /* return a pointer to the newnode so the calling function can use it if it wants to.
         * You could return NULL if the memory wasn't allocated to let the calling function
         * know (see comment about about checking return value of malloc())
         */
        return newnode;
    }
    
    int main(void)
    {
        struct list mylist;
        
        mylist.head = NULL; /* Init to be an empty list */
        
        addNode(&mylist, 5);
        addNode(&mylist, 10);
        
        show(&mylist);
        
        /* ADD a function here to delete all the nodes in the list */
        
        return 0;
    }
    Edit: Since I'd mentioned the for loop way, here is the alternative code that uses a for loop. As you can see it's essentially the same as in show (it traverses the list in the same way, it just doesn't print the value on ->n along the way)

    Code:
    struct node *addNode(struct list *mylist, int value)
    {
        struct node *newnode;
        
        newnode = malloc(sizeof *newnode);
        /* Should add error checking here to ensure malloc() succeeded */
        newnode->next = NULL;
        newnode->n = value;
        
        if (mylist->head == NULL) { /* If list is empty then add at head */
            mylist->head = newnode;
        } else { /* otherwise find the tail (last node) of the list and add there */
            /* find the tail, AKA 'last' */
            struct node *p;
            for (p = mylist->head; p->next != NULL; p = p->next)
                ;
            
            /* p now points to the tail of the list. Add our new node here. p->next is currently NULL so change it to point to our new node */
            p->next = newnode;
        }
        
        /* return a pointer to the newnode so the calling function can use it if it wants to.
         * You could return NULL if the memory wasn't allocated to let the calling function
         * know (see comment about about checking return value of malloc())
         */
        return newnode;
    }
    I should add that it's relatively rare that I write working code in response to questions, but I think that the example code in the Wikipedia article is somewhat misleading (as mentioned). You went to the effort of at least reading the page, which many people don't seem to even bother doing, so I decided to use what I hope are better variable names. Aside from the naming of the variables the code is exactly the same but I hope it helps

    [1] I say probably because there are other ways to implement linked lists and if you were using a dummy node -- which can eliminate the need to deal with empty lists separately -- then you'd be doing things differently (not passing pointers to pointers)
    Last edited by Hodor; 12-30-2019 at 01:40 AM.

  9. #9
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,791
    As you can see it's essentially the same
    Maybe it's obvious but I should clarify that bit. I mean it's "essentially" the same in that it's traversing along the list. Not exactly the same though. In show() it goes until every single node has been visited and then stops. In the addNode() function it stops when there is no next node

  10. #10
    Registered User
    Join Date
    Nov 2019
    Posts
    90
    Quote Originally Posted by Hodor View Post
    Maybe you're just having trouble understanding the Wikipedia example

    I should add that it's relatively rare that I write working code in response to questions, but I think that the example code in the Wikipedia article is somewhat misleading (as mentioned). You went to the effort of at least reading the page, which many people don't seem to even bother doing, so I decided to use what I hope are better variable names. Aside from the naming of the variables the code is exactly the same but I hope it helps
    Hodar Many thanks for you. You explained very well. It help me a lot

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why this program show me unlimited number of ans?
    By abhijitnumber1 in forum C Programming
    Replies: 1
    Last Post: 07-02-2012, 09:07 AM
  2. Show list
    By Thoggle in forum C++ Programming
    Replies: 3
    Last Post: 09-06-2010, 11:12 AM
  3. Show a number in the MessageBox
    By Coding in forum Windows Programming
    Replies: 17
    Last Post: 01-27-2008, 03:01 PM
  4. Show random number
    By q(-^-)P in forum C++ Programming
    Replies: 12
    Last Post: 09-01-2003, 06:50 AM
  5. Program to show the number of occurrences of words...
    By Nutshell in forum C Programming
    Replies: 5
    Last Post: 01-26-2002, 06:44 PM

Tags for this Thread