Thread: Inserting a new node at the end of a linked-list

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jun 2020
    Posts
    5

    Question Inserting a new node at the end of a linked-list

    Hi everyone!

    I'm trying to write a program that lets the user append nodes at the end of a linked list. It kinda works but the main problem is that it doesn't actually create any new nodes later on, the function I've written creates one new node and then just keeps on changing its values over and over again.

    Code:
    static void append(Node *_tail, unsigned _id) {
        Node temp = { .id = _id, .next = NULL };
    
    
        if (_tail == NULL) {
            _tail = &temp;
        } else {
            _tail->next = &temp;
            _tail = &temp;
        }
    }
    I've also tried dynamically allocating memory for the nodes with malloc() and calloc() but that gave me the same results. What am I doing wrong?

    Here's the main() function if you were wondering.

    Code:
    int main(void) {
        unsigned input;
        Node n3 = { .id = 3, .next = NULL };
        Node n2 = { .id = 2, .next = &n3 };
        Node n1 = { .id = 1, .next = &n2 };
        Node *head = &n1, *tail = &n3;
    
    
        for (;;) {
            printf("Enter an ID: "), scanf("%u", &input);
    
    
            append(tail, input);
    
    
            for (Node *i = head; i != NULL; i = i->next) {
                printf("ID: %u\n", i->id);
            }
        }
    
    
        return 0;
    }
    Last edited by bld; 04-08-2021 at 12:48 PM. Reason: Formatting

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inserting a node at the tail of singly linked list
    By ghoul in forum C++ Programming
    Replies: 6
    Last Post: 10-23-2020, 07:08 AM
  2. How to Inserting a new node in a linked list
    By abhi143 in forum C Programming
    Replies: 3
    Last Post: 11-07-2019, 01:15 PM
  3. Problem in output of code(Inserting node in linked list)
    By Kunal1997 in forum C Programming
    Replies: 3
    Last Post: 09-03-2016, 01:37 AM
  4. Two Question About Inserting Node In the Linked List
    By hefese in forum C Programming
    Replies: 10
    Last Post: 08-07-2012, 12:24 PM
  5. Replies: 7
    Last Post: 11-04-2010, 01:18 PM

Tags for this Thread