Sunday, November 09, 2014

Implementing Reversal& Merging Operations on Linked List - Data Structures - C++ Program (Procedural)

Problem Question


To implement Linked Lists and perform reversal of list and union of lists

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 nodes in doubly linked list).



In this program we use a struct to implement the node of our linked list. We will implement addition function to get some data in linked list before we can perform reversal/union on it. 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.4.cpp*
*@Programming Paradigm: Procedural*
*@Language: C++*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Rogue Coder*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 09-11-2014*
*/

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

void addAtLast(node** rootNode);
void reverseList(node** rootNode);
void unionOfLists(node** rootOfListA, node** rootOfListB);
void displayList(node* rootNode);

int main()
{
  int choice;
  node *startOtherList = NULL, *startList = NULL;
  std::cout << "Welcome to LinkedList v1.4" << std::endl << "Made by Rogue Coder" << std::endl;
  do
  {
    std::cout << std::endl << "1 : Add a Node to the list" <<
         std::endl << "2 : Reverse the List" <<
         std::endl << "3 : Merge 2 lists" <<
         std::endl << "4 : Display List" <<
         std::endl << "5 : Exit" <<
         std::endl << "Enter your choice : ";
    std::cin>>choice;
    switch(choice)
    {
    case 1:
      std::cout << "Which list would you like to add to?(1/2): ";
      std::cin >> choice;
      switch(choice)
      {
      case 1:
        addAtLast(&startList);
        break;
      case 2:
        addAtLast(&startOtherList);
        break;
      default:
        std::cout << std::endl << "!!!Wrong Choice! Please enter 1 or 2!!!" << std::endl;
        choice = 1;
        break;
      }
      break;
    case 2:
      std::cout << "Which list would you like to reverse?(1/2): ";
      std::cin >> choice;
      switch(choice)
      {
      case 1:
        reverseList(&startList);
        break;
      case 2:
        reverseList(&startOtherList);
        break;
      default:
        std::cout << std::endl << "!!!Wrong Choice! Please enter 1 or 2!!!" << std::endl;
        choice = 2;
        break;
      }
      break;
    case 3:
      std::cout << "How would you like to perform union of the lists?" <<
           std::endl << "1. ListA->ListB" <<
           std::endl << "2. ListB->ListA" <<
           std::endl << "Your choice: ";
      std::cin >> choice;
      switch(choice)
      {
      case 1:
        unionOfLists(&startList, &startOtherList);
        break;
      case 2:
        unionOfLists(&startOtherList, &startList);
        break;
      default:
        std::cout << std::endl << "!!!Wrong Choice! Please enter 1 or 2!!!" << std::endl;
        choice = 3;
        break;
      }
      break;
    case 4:
      std::cout << "Which list would you like to display?(1/2): ";
      std::cin >> choice;
      switch(choice)
      {
      case 1:
        displayList(startList);
        break;
      case 2:
        displayList(startOtherList);
        break;
      default:
        std::cout << std::endl << "!!!Wrong Choice! Please enter 1 or 2!!!" << std::endl;
        choice = 4;
        break;
      }
      break;
    case 5:
      std::cout<<std::endl<<"Thank you for using LinkedList v1.4"<<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 addAtLast(node** rootNode)
{
  node* newNode = new node;
  std::cout<<std::endl<<"Enter data : ";
  std::cin>>newNode->data;
  if(*rootNode == NULL)
  {
    *rootNode = newNode;
  }
  else
  {

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

void reverseList(node** rootNode)
{
  if (*rootNode == NULL)
  {
    std::cout<<std::endl<<"\aList Empty\a"<<std::endl;
  }
  else
  {
    node *previousNode = NULL, *nextNode, *currentNode = *rootNode;
    while(currentNode != NULL)
    {
      nextNode = currentNode -> next;
      currentNode -> next = previousNode;
      previousNode = currentNode;
      currentNode = nextNode;
    }
    *rootNode = previousNode;
    std::cout << std::endl << "Linked List is reversed!";
  }
}

void unionOfLists(node** rootOfListA, node** rootOfListB)
{
  if (*rootOfListA == NULL)
  {
    *rootOfListA = *rootOfListB;
  }
  else
  {
    node* currentNode = *rootOfListA;
    while (currentNode -> next != NULL)
    {
      currentNode = currentNode -> next;
    }
    currentNode -> next = *rootOfListB;
  }
  *rootOfListB = NULL;
}

void displayList(node* rootNode)
{
  node *currentNode = rootNode;
  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.

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




void addAtLast(node** rootNode)
{
node* newNode = new node;
std::cout<>newNode->data;
if(*rootNode == NULL)
{
*rootNode = newNode;
}
else
{
node* currentNode = *rootNode;
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. The argument stores the rootNode of the List to which we are adding to. Since this program is capable of merging two lists too, we first need 2 lists, right? The function asks for user input and the data is stored in the memory location pointed to by ‘newNode’ 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 to this memory location is returned, which we capture in the variable ‘newNode’. After the user input the program checks if the list to which we are adding to is empty, which we come to know if the ‘rootNode’, 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 ‘rootNode’ 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 reverseList(node** rootNode)
{
if (*rootNode == NULL)
{
std::cout< next;
currentNode -> next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
*rootNode = previousNode;
std::cout << std::endl << "Linked List is reversed!"; } }
-> In this function we take the argument as the root node of the list which is to be reversed. The function first checks if the list is empty, and returns a message to user if so is the case. Otherwise the reversal of list kicks off. Pointer, ‘previousNode’ is used to hold the address of the node previous to the current node. Similarly ‘nextNode’ is used to point to the location of the node next to the current node. We initialise ‘currentNode’ to be rootNode of the list to be reversed. Then as we traverse from rootNode to the end of list, we keep on storing the address of currentNode in nextNode pointer, and the currentNode’s next is made to point to previous node, thus reversing a link. Previous node is then assigned current node’s address, and current node is assigned address of next node(actual next node). Hence we have reversed a link in the list, and the currentNode pointer is pointing to the next node in original list. We traverse this way until currentNode point to NULL. The list is reversed, but the rootNode pointer is still pointing to the original first node of the list. Hence, we make it to point to the ‘previousNode’ pointer, which is the actually the last node in original list when the loop ends. Hence the list is reversed.

void displayList(node* rootNode)
{
node *currentNode = rootNode;
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. The argument to the function holds the rootNode of the list which is to be displayed. In the start of the function, we have assigned a new pointer, ‘currentNode’, to point to the root node, ‘rootNode. 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