Thread: Add not after previous node

  1. #1
    Registered User
    Join Date
    Oct 2019
    Posts
    68

    Add not after previous node

    Hi,

    I want to make function that add new node after previous node. if the list is empty add the first node and then add new node after previous node

    Code:
    #include <stdio.h>#include <stdlib.h>
    
    
    struct Node
    {
    	int Data;
        struct Node * Next;
    };
    
    
    struct Node * Add_New ( int n, struct Node * Pointer)
    {
    
    
    	struct Node *New = malloc(sizeof(*New));
    	
    	New-> Data = n;
    	New-> Next = Pointer;
    	
    	return Pointer;
    }
    	             
    int main ()
    {
    	struct Node * Head = NULL;
    	
    	return 0;
    }
    any help would highly appreciated

    Thank you

  2. #2
    Registered User
    Join Date
    Oct 2019
    Posts
    68
    Every function call new node will add to list. The pointer will always point to the address of the next node. when node is last node pointer will point to null. But i don't think my function is doing that How to make correct function so that I can make my list

  3. #3
    Registered User
    Join Date
    Dec 2017
    Posts
    935
    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    typedef struct Node
    {
        int data;
        struct Node *next;
    } Node;
     
    Node *AddNode(int data, Node *prev)
    {
        Node *node = malloc(sizeof *node);
        node->data = data;
        if (prev)
        {
            node->next = prev->next;
            prev->next = node;
        }
        else
        {
            node->next = NULL;
            prev = node;
        }
        return prev;
    }
     
    void print(Node *node)
    {
        for ( ; node; node = node->next)
            printf("%d ", node->data);
        printf("\n");
    }
     
    int main()
    {
        Node *head = NULL;
        for (int i = 0; i < 8; ++i)
            head = AddNode(i, head);
        print(head);
        return 0;
    }
    If you want the truth to stand clear before you, never be for or against. - Sent-ts'an

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Quadtree Node -> pointers to the children node
    By yahn in forum C++ Programming
    Replies: 2
    Last Post: 04-13-2009, 06:38 PM
  2. Replies: 0
    Last Post: 09-16-2008, 05:04 AM
  3. NODE *RemoveDuplicates(NODE *p, NODE *q);
    By xnicky in forum C Programming
    Replies: 3
    Last Post: 12-03-2006, 05:30 PM
  4. First Last Next and Previous
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 04-17-2002, 10:05 AM
  5. Replies: 5
    Last Post: 10-04-2001, 03:42 PM

Tags for this Thread