Simple Linked List

#include <iostream> #include <cstdlib> using namespace std; //declaration of structure for node of list struct numbers{ int value; struct numbers *next; }; //the list is a pointer to structure numbers struct numbers *listNumbers; int main(){ char answer; cout<<"Welcome to my first example of list"<<endl; do{ //two pointers to a structure numbers which is going to have //the address of a new node and the current node struct numbers *newNumber, *currentNumber; //we need to allocate memory for the new node of the list newNumber = (struct numbers *) malloc( sizeof(struct numbers) ); cout<<"Introduce a number: "; //set the value for the number node cin>>newNumber->value; //then the pointer to a next node must be null //because it is a new node so there is no next node newNumber->next = NULL; if(!listNumbers){ //if this is the first node then the list of numbers is null //so we need to set the list numbers with the first node listNumbers = newNumber; currentNumber = newNumber; } else{ //if the listnumbers have at least one node then //the pointer next of the previous node will point to our new node currentNumber->next = newNumber; //and then current node will be our new node currentNumber = newNumber; } cout<<"Add another? (y=yes, n=no)"; cin>>answer; }while(answer != 'n'); //if the list of numbers has elements then if(listNumbers){ struct numbers *current; //the current node is the first node of the list //as the listNumbers is the first node current = listNumbers; //we going to iterate through the list //if the current node is not a null address while(current){ cout<<current->value<<"-->"; //we assign the current node to be the next node //as I said before if the next node is the value null it will break the loop current = current->next; } cout<<"null"<<endl; } return 0; }
This is a very basic example of how to make a simple linked list using the C++ language, my purpose was to use only the C language but I don't like the way I have to manage the input and output so I decided to use the cout and cin objects of the C++. I think this program will work the same if I do it with pure C.
Thank you and I hope it will be helpful to someone.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.