Saturday, September 27, 2014

Implementing Addition Operation on a Linked List - Data Structures - C++ Program (Procedural)

Problem Question


To implement Linked List and perform addition operation on it

Explanation of Problem


In this program we would be implementing a Linked List. Make sure you have a strong understanding of pointers to understand Linked Lists. A linked list is a basic data structure that is used in dynamic memory allocation applications. It comprises of ‘nodes’ which are linked together to form a sequence of nodes called Linked List. The linkage is done using memory addresses of adjacent nodes (next node in singly linked list, and both next & previous node in doubly linked list).



In this program we use a struct to implement the node of our linked list. Adding a new node to the list means, creating a new node structure, allocating memory to it and linking it to the list.

Code


#include <iostream>
/**@Title: LinkedList v1.1.cpp*
*@Programming Paradigm: Procedural*
*@Language: C++*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Rogue Coder*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 27-09-2014*
*/

struct node
{
  int data;
  node* next;
};

node* startList;

void addAtBeginning();
void addAtPosition();
void addAtLast();
void displayList();

int main()
{
  int choice;
  std::cout << "Welcome to LinkedList v1.1" << std::endl << "Made by Rogue Coder" << std::endl;
  do
  {
    std::cout << std::endl << "1 : Add a Node at beginning" <<
         std::endl << "2 : Add a Node at some position" <<
         std::endl << "3 : Add a Node at last" <<
         std::endl << "4 : Display List" <<
         std::endl << "5 : Exit" <<
         std::endl << "Enter your choice : ";
    std::cin>>choice;
    switch(choice)
    {
    case 1:
      addAtBeginning();
      break;
    case 2:
      addAtPosition();
      break;
    case 3:
      addAtLast();
      break;
    case 4:
      displayList();
      break;
    case 5:
      std::cout<<std::endl<<"Thank you for using LinkedList v1.1"<<std::endl<<"Made by Rogue Coder"
           <<std::endl<<"Press any key to exit"<<std::endl;
      break;
    default:
      std::cout<<"\a\aWrong Choice\a\a"<<std::endl;
      break;
    }
  }
  while(choice != 5);
  std::cin.get();
  return 0;
}

void addAtBeginning()
{
  node* newNode = new node;
  std::cout<<std::endl<<"Enter data : ";
  std::cin>>newNode->data;
  if(startList == NULL)
  {
    startList = newNode;
    newNode -> next = NULL;
  }
  else
  {
    newNode -> next = startList;
    startList = newNode;
  }
}

void addAtPosition()
{
  char wishToAdd;
  if (!startList)
  {
    std::cout << std::endl << "The list is empty, do you wish to add at the beginning of the list?(y for yes): ";
    std::cin >> wishToAdd;
    if (wishToAdd == 'y')
    {
      addAtBeginning();
      return;
    }
  }
  else
  {
    node* currentNode = startList;
    int positionToAddAt, loopCounter = 1;
    std::cout << std::endl << "Enter the position where to add at: ";
    std::cin >> positionToAddAt;
    if (positionToAddAt <= 1)
    {
      std::cout << "\a\aDo you wish to add at beginning of the list?(y for yes): ";
      std::cin >> wishToAdd;
      if (wishToAdd == 'y')
      {
        addAtBeginning();
        return;
      }
    }
    else
    {
      while(currentNode)
      {
        currentNode = currentNode -> next;
        loopCounter++;
      }
      if (positionToAddAt > loopCounter)
      {
        std::cout << "\a\aLast node encountered. The position you wish does not exist in the list yet."
             << std::endl << "Do you wish to enter at the end of list?(y for yes): ";
        std::cin >> wishToAdd;
        if (wishToAdd == 'y')
        {
          addAtLast();
          return;
        }
      }
      else
      {
        currentNode = startList;
        for (loopCounter = 1; loopCounter < positionToAddAt - 1; loopCounter++)
        {
          currentNode = currentNode -> next;
        }
        node* newNode = new node;
        std::cout << std::endl << "Please enter the data: ";
        std::cin >> newNode -> data;
        newNode -> next = currentNode -> next;
        currentNode -> next = newNode;
        return;
      }
    }
  }
  std::cout << "\aNo node created...\a";
}

void addAtLast()
{
  node* newNode = new node;
  std::cout<<std::endl<<"Enter data : ";
  std::cin>>newNode->data;
  if(startList == NULL)
  {
    startList = newNode;
  }
  else
  {

    node* currentNode=startList;
    while(currentNode->next != NULL)
    {
      currentNode=currentNode->next;
    }
    currentNode->next=newNode;
  }
  newNode->next=NULL;
}

void displayList()
{
  node *currentNode = startList;
  if(currentNode == NULL)
  {
    std::cout<<std::endl<<"\aList Empty\a"<<std::endl;
  }
  else
  {
    std::cout<<std::endl;
    while(currentNode != NULL)
    {
      std::cout<<currentNode->data<<"->";
      currentNode=currentNode->next;
    }
    std::cout<<"End of List"<<std::endl;
  }
}



Explanation of Code


#include <iostream> -> The compiler calls the Preprocessor to include the IOSTREAM(Standard Input / Output Streams Library) header file into the program, thus letting the use of the Standard Input / Output Streams functions like std::cin and std::cout. As per C++11 specification, including <iostream> automatically includes also <ios>, <streambuf>, <istream>, <ostream> and <iosfwd>.

int main() -> The entry point of the program where the execution starts. This function has to be named main. As per the ANSI specification, the return type has to be int. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

std::cin (extern istream cin) -> Standard Input Stream, and object of class istream. It is generally used with the extraction operator (>>), though we can use member functions like get (cin.get()), read (cin.read()), etc. for the input. The use of extraction operator is much more popular due to the fact that it aids in getting formatted input.

std::cout (extern ostream cout) -> Standard Output Stream, and object of class ostream. It is generally used with the insertion operator (<<), though we can use member functions like write (cout.write()) for the output. The use of insertions operator is much more popular due to the fact that it aids in giving formatted output.

std::endl (ostream& endl (ostream& os)) -> This is a function which is used to insert a newline character and flush the stream. Because this function is a manipulator, it is designed to be used alone with no arguments in conjunction with the insertion (<<) operations on output streams.

struct node
{
int data;
node* next;
};
->This is where we create the struct node that is going to be the building block of our linked list. It comprises of an int ‘data’ where the user shall store the data they wish. Please note, you can use as many variables and of as many types in the struct, but be sure you handle them correctly. For simplicity we have used int type in our case. The other variable inside our node is ‘next’, which is a pointer to node. This would be used to build the linkage between the nodes of our linked list. ‘next’ is going to hold the address of the next node in the sequence.

node* startList; -> The global pointer ‘startList’ which we are going to use to point to the first node/root node/ start node of the linked list, we are going to implement in this program.

int choice; -> This variable ‘choice’ will be used for the user’s choice in the menu driven program.



void addAtBeginning()
{
node* newNode = new node;
std::cout<<std::endl<<"Enter data : ";
std::cin>>newNode->data;
if(startList == NULL)
{
startList = newNode;
newNode -> next = NULL;
}
else
{
newNode -> next = startList;
startList = newNode;
}
}
-> This is the function that will be used for adding a new node at the beginning of the list. To do so, the basic logic is creating a new node and assigning it to be the start node and the next of this to point at the earlier start node. Now let’s examine how we implement this logic in our program. So we get the user’s input of the data that they wish to enter into the list. After the user input the program checks if the list is empty which we come to know if the ‘startList’, i.e., root node of the linked list is initialised as yet or not. If the root node is not yet initialised for our list, we make the ‘startList’ pointer to point to the ‘newNode’ we just created. Else, the newNode’s next is assigned as the current start node of the list. Then we assign the startList to point to the newNode. Thus, we get the new node at beginning of the list.



void addAtPosition()
{
char wishToAdd;
if (!startList)
{
std::cout << std::endl << "The list is empty, do you wish to add at the beginning of the list?(y for yes): ";
std::cin >> wishToAdd;
if (wishToAdd == 'y')
{
addAtBeginning();
return;
}
}
else
{
node* currentNode = startList;
int positionToAddAt, loopCounter = 1;
std::cout << std::endl << "Enter the position where to add at: ";
std::cin >> positionToAddAt;
if (positionToAddAt <= 1)
{
std::cout << "\a\aDo you wish to add at beginning of the list?(y for yes): ";
std::cin >> wishToAdd;
if (wishToAdd == 'y')
{
addAtBeginning();
return;
}
}
else
{
while(currentNode)
{
currentNode = currentNode -> next;
loopCounter++;
}
if (positionToAddAt > loopCounter)
{
std::cout << "\a\aLast node encountered. The position you wish does not exist in the list yet."
<< std::endl << "Do you wish to enter at the end of list?(y for yes): ";
std::cin >> wishToAdd;
if (wishToAdd == 'y')
{
addAtLast();
return;
}
}
else
{
currentNode = startList;
for (loopCounter = 1; loopCounter < positionToAddAt - 1; loopCounter++)
{
currentNode = currentNode -> next;
}
node* newNode = new node;
std::cout << std::endl << "Please enter the data: ";
std::cin >> newNode -> data;
newNode -> next = currentNode -> next;
currentNode -> next = newNode;
return;
}
}
}
std::cout << "\aNo node created...\a";
}
-> In this function we let the user decide a position in our list where they wish to add a node in the list. But since the user can enter positions like negative and those which don’t yet exist on the list, we need to handle those cases elegantly. So in our function we let the user give their choice what they wish to do in such special cases. To handle this choice of the user we declare a char type variable ‘wishToAdd’.

Now we first check if the list is empty. If so is the case, we prompt the user with a message and ask if the user would like to add a node at the beginning of the list. If the user enters ‘y’ indicating yes as their choice, we call the function addAtBeginning() and return. The return statement is necessary so that the control doesn’t fall below this level in the program. If the user enters something else, “No node created” is displayed to the user.

If the list wasn’t empty, we ask the user to enter the position where they’d wish to enter the new node. If the position is less than or equal to 1, that means the only valid position where the new node can be entered is the beginning of the list. So here too we shall prompt the user if they’d like to create a new node at beginning. If the user indicates yes, we call the function addAtBeginning(), else “No node created” is displayed to user. Please note the return statement here too has the same importance as earlier, else even if the node is created, “No node created” would be displayed.

If the user didn’t enter a position less than or equal to 1, we count the number of exisiting nodes in the list. For this we use the currentNode to store the location same as that in startList. Then we traverse through the list until we encounter a null node, i.e. End Of List. We increment the loopCounter at each iteration. Now we have the number of nodes in the list. If the position that user enters is greater than this number, that means the user wishes to enter at a position which doesn’t exist in the list yet. Thus the user prompted of the case and asked if they wish to enter at the end of the list. If the user chooses so, the control is sent to the function addAtLast(). Again, return statement has the same effect here. If the user doesn’t wish to add a new node at the end of list, then ‘No Node created’ is displayed to the user.

Now if the user entered a correct position, that means, which is not less than or equal to 1, is not greater than the number of nodes in the list, we set the currentNode to point to the start node again and we traverse through the list upto the point where the user wishes to enter in the list. Now how do we achieve this? We start from the first node, and we go 2 nodes before the node where the user wishes to enter new node. Like, if the user wants to enter the new node at position 4, we start from root node. The loop runs till loopCounter becomes from 1 to 1 less than the position where the user wishes to enter, i.e., 2 in the case we are discussing here. Since we are setting the currentNode to point to next node in each iteration, at the end of list, currentNode points to(node 3 in this case) one node before the position where the user wishes to enter the new node. Now, we create a new node and ask for user’s input for the data to be stored in this node. Then we set the ‘next’ of our new node to point to the next of the currentNode(which would be the actual 4th node in this case), i.e., the node currently at position where the user wished to enter the new node. And then, we set the currentNode’s next to point to the newNode(thus newNode is now at position 4). Again return statement has the same significance as we discussed earlier.



void addAtLast()
{
node* newNode = new node;
std::cout<<std::endl<<"Enter data : ";
std::cin>>newNode->data;
if(startList == NULL)
{ startList = newNode; }
else
{

node* currentNode=startList;
while(currentNode->next != NULL)
{ currentNode=currentNode->next; }
currentNode->next=newNode;
}
newNode->next=NULL;
}
-> This function is used to add a new node at the end of our linked list. It asks for user input and the data is stored in the ‘newNode’ which is the pointer to the new node that we are going to add to our list. The first statement of this function means, memory is allocated for a node type variable and a pointer is returned which we capture in the variable ‘newNode’. After the user input the program checks if the list is empty which we come to know if the ‘startList’, i.e., root node of the linked list is initialised as yet or not. If the root node is not yet initialised for our list, we make the ‘startList’ pointer to point to the ‘newNode’ we just created. Else, we traverse through the list. Starting from the root node, we hold the position in a new pointer, ‘currentNode’. Since the last node’s ‘next’ won’t point to any node, thus we use currentNode->next != NULL for that. Till so is the case, we keep on assigning the address of the next node in sequence to the pointer ‘currentNode’. So as and when we encounter the last node in the list, we come out of the loop. The pointer ‘currentNode’ now holds the address to the last node in the list. So we define the ‘next’ for this last node of ours as the newNode we just created. Now the next of newNode is set to NULL, hence the newNode is added at the end of the list.

void displayList()
{
node *currentNode = startList;
if(currentNode == NULL)
{ std::cout<<std::endl<<"\aList Empty\a"<<std::endl; }
else
{
std::cout<<std::endl;
while(currentNode != NULL)
{
std::cout<<currentNode->data<<"->";
currentNode=currentNode->next;
}
std::cout<<"End of List"<<std::endl;
}
}
->This is the function that will be used for traversal of the linked list. We would display the elements of the list as we traverse it. In the start of the function, we have assigned a new pointer, ‘currentNode’, to point to the root node, ‘startList’. Then, we check if the list is empty by checking if the currentNode is pointing to null. If currentNode is not pointing to NULL, we traverse the list using a while loop. We check until the currentNode points to null, we display the ‘data’ of the node pointed to by ‘currentNode’, followed by setting ‘currentNode’ to point to the next node in sequence. For better presentation, we separate each element by an arrow ‘->’ printing it after printing the data of each node. And thus we print ‘End of List’ at the end. Both these things we have added for presentation purposes only.

do{..}while() -> The program loop which encapsulates the whole program. Until the user chooses to exit the program, the control loops within this.

exit(0); -> This function is used to exit the program with an error code as it's argument. '0' implies normal exit. Other values are used for debugging purposes.

std::cin.get() -> This statement is used to pause our program, until user presses a key. This function is not necessary in your program, I use it to see my outputs at a paused screen. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)




Download Source Code



No comments:

Post a Comment

Need help?