Problem Question
To implement intersection operation on Linked List.
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. We will implement addition function to get some data in linked list before we can perform desired operations 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.
Consider we have two linked lists. Intersection means finding those unique nodes which are common to both the lists. For example, if we have two lists, 1->2->3->4 and 1->1->2->8->4->6, then the intersection is 1->2->4.
Code
#include<iostream>
/**@Title: LinkedList v1.10.cpp*
*@Programming Paradigm: Procedural*
*@Language: C++*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Rogue Coder*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 09-02-2015*
*/
struct node
{
  int data;
  node* next;
};
void addAtLast(node** rootNode, int userData);
void intersection(node** rootNodeFirst, node** rootNodeSecond, node** rootIntersect);
void displayList(node* rootNode);
bool findNode(node* rootNode, int findData);
int main()
{
  int choice, userInput;
  node *startListFirst = NULL, *startListSecond = NULL, *intersect = NULL;
  std::cout << "Welcome to LinkedList v1.10" << std::endl << "Made by Rogue Coder" << std::endl;
  do
  {
    std::cout << std::endl << "1 : Add a Node to the list 1" <<
         std::endl << "2 : Add a Node to the list 2" <<
         std::endl << "3 : Get Intersection" <<
         std::endl << "4 : Display List" <<
         std::endl << "5 : Exit" <<
         std::endl << "Enter your choice : ";
    std::cin>>choice;
    switch(choice)
    {
    case 1:
        std::cout<<std::endl<<"Enter data : ";
        std::cin>>userInput;
        addAtLast(&startListFirst, userInput);
        break;
    case 2:
        std::cout<<std::endl<<"Enter data : ";
        std::cin>>userInput;
        addAtLast(&startListSecond, userInput);
        break;
    case 3:
        intersect = NULL;
        intersection(&startListFirst, &startListSecond, &intersect);
        displayList(intersect);
        break;
    case 4:
        std::cout<<"List 1: ";
        displayList(startListFirst);
        std::cout<<"List 2: ";
        displayList(startListSecond);
        break;
    case 5:
      std::cout<<std::endl<<"Thank you for using LinkedList v1.10"<<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, int userData)
{
   node* newNode = new node;
   newNode -> data = userData;
   if(*rootNode == NULL)
   {
      *rootNode = newNode;
   }
   else
   {
       node* currentNode = *rootNode;
       while(currentNode->next != NULL)
       {
           currentNode = currentNode->next;
       }
       currentNode -> next = newNode;
   }
   newNode -> next = NULL;
}
void intersection(node** rootNodeFirst, node** rootNodeSecond, node **rootIntersect)
{
    if (*rootNodeFirst == NULL || *rootNodeSecond == NULL)
    {
        *rootIntersect = NULL;
        return;
    }
    node *currentNode = *rootNodeFirst;
    while (currentNode)
    {
        node *thisNode = *rootNodeSecond;
        while (thisNode)
        {
            if (thisNode -> data == currentNode -> data && ! findNode(*rootIntersect, thisNode -> data))
            {
                addAtLast(rootIntersect, thisNode -> data);
            }
            thisNode = thisNode -> next;
        }
        currentNode = currentNode -> next;
    }
}
bool findNode(node* rootNode, int findData)
{
    node *currentNode = rootNode;
    while (currentNode)
    {
        if (currentNode -> data == findData)
            return true;
        currentNode = currentNode -> next;
    }
    return false;
}
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.
using namespace std; -> In modern IDEs, we have to explicitly write std::cout instead of cout to use the ostream cout object. Namespace std helps in easing off the pain of writing std:: again and again. Though make sure you are not trapped! The classes defined in std should not be redefined by you. So in case you want to define a class 'distance', you can't do so if you have used std namespace. Though you can define 'Distance' (capital D).
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.
{
  int data;
  node* next;
}; ->
node* startListFirst; node* startListSecond; -> These are the pointers, which we are going to use to point to the first node / root node / start node of the linked list, that 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.
{
   node* newNode = new node;
   newNode -> data = userData;
   if(*rootNode == NULL)
   {
      *rootNode = newNode;
   }
   else
   {
       node* currentNode = *rootNode;
       while(currentNode->next != NULL)
       {
           currentNode = currentNode->next;
       }
       currentNode -> next = newNode;
   }
   newNode -> next = NULL;
} ->
{
    node *currentNode = rootNode;
    while (currentNode)
    {
        if (currentNode -> data == findData)
            return true;
        currentNode = currentNode -> next;
    }
    return false;
} ->
{
    if (*rootNodeFirst == NULL || *rootNodeSecond == NULL)
    {
        *rootIntersect = NULL;
        return;
    }
    node *currentNode = *rootNodeFirst;
    while (currentNode)
    {
        node *thisNode = *rootNodeSecond;
        while (thisNode)
        {
            if (thisNode -> data == currentNode -> data && ! findNode(*rootIntersect, thisNode -> data))
            {
                addAtLast(rootIntersect, thisNode -> data);
            }
            thisNode = thisNode -> next;
        }
        currentNode = currentNode -> next;
    }
} ->
We first check if either list empty. If so, we simply return, since that means there would be nothing common between the lists. Else, we traverse through the lists and seek common values between them. If such value is found, we add it to the intersection output list, provided it is not already present there. We check the latter using our helper function findNode, passing it the value we have found and the rootNode of the intersection output linked list.
The outer while loop traverses throuhg list one, and the inner loop traverses through list two, comparing each node of the lists. if (thisNode -> data == currentNode -> data && ! findNode(*rootIntersect, thisNode -> data)) statement checks if the value is present in both the lists, and is not yet fed to intersection output. The first half compares the values. The second half checks if the value is present i nthe output already or not. Since we want to keep only unique values going in, we need this second check in place.
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;
  }
} ->
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.
No comments:
Post a Comment
Need help?