Linked List

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mircead2014
    New Member
    • Feb 2014
    • 4

    Linked List

    Hi.
    I am a beginner in linked list programming.
    I have made a program, but I am not sure if it is a good implementation.
    The code compile and the results are very good, like i expected.
    I want to give me some advices.
    Thank you.

    Code:
     Inserting a new node at the end of the list.
     The new node inserted is the last one in the list.
    
    #include<stdio.h>
    #include<stdlib.h>
    #include<malloc.h>
    
    struct node
    {
        int numar;
        struct node *next;
    };
    
    struct node *Create_list()
    {
        struct node *new_node, *first = NULL, *temp = NULL;
        int n;
        char choice = 1;
        while(choice == 1)
        {
            new_node  = (struct node *)malloc(sizeof(struct node));
            if(new_node == NULL)
            {
                printf("\n Node creation failed!\n");
                return NULL;
            }
            printf("\n Introduceti elementele : ");
            scanf("%d", &new_node->numar);
            if(first != NULL)
            {
                temp->next = new_node;
                temp = new_node;
            }
            else
                first = temp = new_node;
            printf("\n Vreti sa continuati (Apasa \"1\" sau \"0\") ?  ");
            scanf("%d", &choice);
        }
        temp->next = NULL;
        temp = first;
        return temp;
    }
    
    void Print_list(struct node *new_node)
    {
        struct node *temp;
        temp = new_node;
        printf("\n\n\n Lista liniara simplu inlantuita : \n\n");
        while(temp != NULL)
        {
            printf(" %d ->", temp->numar);
            temp = temp->next;
        }
        printf(" NULL\n\n");
    }
    
    int main()
    {
        struct node *new_node;
        new_node = Create_list();
        Print_list(new_node);
    }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Line 29 test temp not first, temp is what you are about to de-reference.

    Line 40 - 41, don't bother copying first to temp, just return first it will be clearer what is going on.

    In a more general sense I would split the collection of data (using printf and scanf away from the logic of adding a new node. I would have a function (Add_node(int value)) that allocated a new node with the supplied value and added it to the list. Then Create_list would do all the use interface stuff and call Add_node to add nodes to the list as required.

    Spliting your program logic away from your user interface code makes it easier to re-use your program logic in new situations.

    Comment

    Working...