Saturday, 11 April 2015

Code for Creating a New Node in C++ (Algorithm Style)

struct Node{
int data;
Node *link;
};

void main(){
Node *start;
start = NULL;
start = new Node;
start->data=2;
start->link=NULL;
cout<<start->data;
}


Explanation:


  • Line 1 to 4: We have created a new structure named Node (we will create Nodes of our linked list using this structure).
  • Line 6: Start of the main() function.
  • Line 7: We have declared a pointer variable, named: start (Note this pointer variable can only point to things which are type of Node).
  • Line 8: We have made "start", a "NULL" (just to make sure that it contains no dummy values).
  • Line 9: "new Node" means create a new Node,
    and "start = new Node" means "start variable is pointing to the newly created node".
  • Line 10: place "10" inside the "data" member of that node, which start is pointing to.
  • Line 11: make "link" member of the node "NULL"
  • Line 12: just output "data" part of the node, which start is pointing to.