Thread: Simple linked list

  1. #1
    Registered User
    Join Date
    May 2021
    Posts
    7

    Simple linked list

    Hi,

    I have created list that only add two numbers

    Code:
    #include<stdio.h>
    #include<stdlib.h> 
        
    struct Node  
    { 
      int X;               // Structure Member 
      struct Node *Next;   // Structure Member 
    }; 
    
    
    int main() 
    { 
      struct Node* Head = NULL; // Declear pointer to structure 
      struct Node* Tail = NULL; // Declear pointer to structure 
       
      Head  = malloc(sizeof(struct Node));  // Allocate memory for Head
      Tail = malloc(sizeof(struct Node));  // Allocate memory for Tail
      
      Head -> X = 1; //assign value in first node 
      Head -> Next = Tail; // assign address of next Node    
         
      Tail -> X = 2; //assign data to second node 
      Tail -> Next = NULL;   
      
      printf(" %d \n", Head -> X); // Print value of First Node 
      printf(" %d \n", Tail -> X); //// Print value of Second Node 
         
       
      return 0; 
    }
    I want to print address of followings
    Head
    Tail
    Head -> X
    TAIL -> X
    Head -> Next
    Tail -> Next

    I don't have any idea how to do it.

    Thank you
    Rahul
    Last edited by Rahul11; 05-10-2021 at 09:16 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,626
    List traversal.
    Code:
    struct Node* temp = Head;
    while ( temp ) {
      // do something with the current node
      printf("This=%p Next=%p Data=%d\n", 
        (void*)temp, (void*)temp->Next, temp->X );
    
      // advance to the next node.
      temp = temp->Next;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple add to linked list
    By c172spilot in forum C++ Programming
    Replies: 4
    Last Post: 04-11-2011, 02:20 PM
  2. Simple Linked List Problem
    By Flamefury in forum C++ Programming
    Replies: 6
    Last Post: 03-20-2010, 07:38 PM
  3. Need help with simple linked list
    By Mahak in forum C++ Programming
    Replies: 5
    Last Post: 09-14-2006, 09:56 AM
  4. simple linked list
    By gmanUK in forum C Programming
    Replies: 2
    Last Post: 12-01-2005, 11:27 AM
  5. Simple linked list question
    By netboy in forum C Programming
    Replies: 3
    Last Post: 07-26-2002, 09:08 PM

Tags for this Thread