......................

Showing posts with label Linked List. Show all posts
Showing posts with label Linked List. Show all posts

Stack Representation of Linked List (C++)

Posted by Unknown On Monday, November 8, 2010 0 comments

#include <iostream.h>
#include <conio.h>
#include <stdlib.h>

class stack
{
private:
  int data;
  stack *next;
public:
  stack() {next = NULL;}
  friend void create(); //function to create a node
  friend void push(stack *&,int); //function to push item on stack
  friend stack* pop(stack *&); //function to delete item from stack
  int getdata() {return data;} //function to return the data of particular node
  ~stack() {delete next;}
};

stack *New,*head,*top;
void create()
{
New = new stack;
New -> next = NULL;
}

void push (stack *&nd,int Item)
{
if(nd == NULL) //if first node
  {
   nd = new stack; //create first node
   nd -> next = NULL; //initialize next pointer field
   nd -> data = Item; //push item
   head = nd; //update head
   top = nd; //update top
   return;
  }

create(); //create a node
New -> data = Item; //push item
top -> next = New; //add to list
top = New; //update top
}

stack* pop (stack *&nd)
{
if(nd == NULL) //if stack is empty
  {
   cout << "\nStack Underflow";
   cout << "\nPress any key to halt...\n";
   getch();
   exit(0);
  }

stack *deleted;
if(top == nd) //if only one node
  {
   deleted = nd;
   top = NULL;
   nd = NULL;
   return deleted;
  }

deleted = top;
stack *temp = head;
while(temp -> next != top) //goto secondlast node
  temp = temp -> next;

temp -> next = NULL;
top = temp; //update top
return deleted;
}

int main()
{
stack *s = NULL;
for(int i = 1;i <= 5;i++) //push 5 items to list
  push(s,5*i);

for(int i = 1;i <= 5;i++)
  {
   stack *result = pop(s); //pop items and
   cout << result -> getdata() << ' '; //display
  }

getch();
return 0;
}

OUTPUT

25 20 15 10 5

Download Original File

Stack using C++.cpp

Addition of Very Long Integers (using Linked List)

Posted by Unknown On Thursday, July 22, 2010 0 comments

/*****************************************************************
 APPLICATION : Addition of Very Long Integers (using Linked List)
 CODED BY    : Ankit Pokhrel
 COMPILED ON : Borland C++ Ver 5.02
 DATE     : 2010 - July - 02
******************************************************************/

#include "iostream.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
#include "string.h"
#include "iomanip.h"

struct Stack //Structure to represent Stack
{
 long int data;
 struct Stack *next,*head,*top; //Pointers to next node,head and top
};

typedef struct Stack node; //Now, node represent Structure Stack

node *New; //Global Variable to represent node

void initialize(node *n)
{
 n -> next = n -> head = n -> top = NULL;
}

void create(node *n)
{
 New = new node; //Create a new node
 New -> data = NULL; //Initialize data
 New -> next = NULL; //Initialize next pointer field
 if(n -> head == NULL) //if first node
  {
  n -> head = New; //Initialize head
   n -> top = New; //Update top
  }
}

void push(node *n,int ITEM)
{
 node *temp = n -> head;
 if(n -> head == NULL) //if First Item is Pushed to Stack
  {
   create(n); //Create a Node
  n -> head -> data = ITEM; //Insert Item to head of List
   return; //Exit from Function
  }

 create(n); //Create a new Node
 New -> data = ITEM; //Insert Item
 while(temp -> next != NULL)
    temp = temp -> next; //Go to Last Node

 temp -> next = New; //Point New node
 n -> top = New; //Update top
}

node* pop(node *n)
{
 node *temp = n -> head,*deleted;
 if(n -> top == NULL) //If the Stack is Empty
  {
    cout << "\nStack Underflow";
    exit(0); //Exit from Program
   }

 if(n -> top == n -> head) //If only one Item
  {
    deleted = n -> head;
    n -> head = n -> top = NULL; //Set head and top to Null
    return deleted; //Return deleted node
   }

 while(temp -> next != n -> top)
  temp = temp -> next; //move pointer temp to second last node

 temp -> next = NULL; //Second last node points to NULL
 deleted = n -> top; //Save topmost node
 n -> top = temp; //Update top
 return deleted; //Return deleted node
}

void display(node *n,int carry)
{
 if(n -> head == NULL) //if no items
  {
    cout << "Stack is empty";
    return;
   }

 node *temp = n -> head;
 if(carry)
  cout << carry;
 cout << setfill('0');
 cout << setw(4) << temp -> data; //Print First Item
 while(temp -> next != NULL)
  {
    temp = temp -> next; //Move to next node
    cout << setfill('0');
    cout << setw(4) << temp -> data; //Print Next Item
   }
}

int count(node *n) //Function to count the number of nodes in a List
{
 if(n == NULL) //if list doesn't exists
  return 0;

 else if(n -> next == NULL) //if only one node
  return 1;

 else
  return (1 + count(n -> next)); //else add 1 and call function count recursively
}

void reverse(node **n) //Function to reverse the List
{
 int N = count((*n) -> head),i = 0;
 long *tempArr = new long[N],*reverse = new long[N]; //Define 2 Arrays
 node *temp = (*n) -> head; //Temp points to node n
 tempArr[i++] = temp -> data; //copy first element to temporary array
 while(temp -> next != NULL) //copy all element to tempArr
  {
    temp = temp -> next;
    tempArr[i++] = temp -> data;
   }

 int j = 0;
 for(i = N - 1;i >= 0;i--)
    reverse[j++] = tempArr[i]; //copy reverse of tempArr to array reverse

//Now copy the elements of array reverse to List  
 i = 0;
 temp = (*n) -> head;
 temp -> data = reverse[i++];
 while(temp -> next != NULL)
  {
    temp = temp -> next;
    temp -> data = reverse[i++];
   }
}

void split(char *opr,node **n) //Function to split the list
{
 int len = strlen(opr);
 int i = len - 1,j;
 char temp[6];
 long value;
 while(i >= 0)
  {
    for(j = 0;j < 4;j++)
     {
     temp[j] = opr[i--];
      if(i < 0)
       {
        j++;
        break;
       }
     }

     temp[j] = '\0';
     strrev(temp);
     value = atol(temp);
     push(*n,value);
   }
}

int main()
{
 node *lint1,*lint2,*result;
 //Allocate memory for lists
 lint1 = new node;
 lint2 = new node;
 result = new node;
 //Initialize all lists to avoid errors
 initialize(lint1);
 initialize(lint2);
 initialize(result);

 char opr1[100],opr2[100];
 long int value;

 //Scan Inputs
 cout << "Enter First Operand : ";
 gets(opr1);
 cout << "Enter Second Operand : ";
 gets(opr2);

 //Divide input into various nodes each containing 1 to 4 characters
 split(opr1,&lint1);
 split(opr2,&lint2);

 //reverse lists lint1 and lint2 because the data is processed from terminal end
 //i.e. Last data will be processed First (LIFO)
 //If we use concept of Queue it is not necessary to reverse the list
 reverse(&lint1);
 reverse(&lint2);

 long data1,data2;
 int carry = 0;
 if(count(lint1 -> head) != 0) //if node exists
    data1 = pop(lint1) -> data; //pop data
 if(count(lint2 -> head) != 0)
    data2 = pop(lint2) -> data;
 value = data1 + data2 + carry;
 carry = value / 10000; //carry can be calculated by dividing value by 10000
 if(carry) //if there is carry
     value = value - carry * 10000; //eliminate carry from value
 push(result,value); //Push value to stack
 int len1,len2,len;
 len1 = count(lint1 -> head);
 len2 = count(lint2 -> head);
 len = (len1 > len2) ? len1 : len2;
 while(len > 0)
  {
    if(count(lint1 -> head) != 0)
     data1 = pop(lint1) -> data;
    else
     data1 = 0;

    if(count(lint2 -> head) != 0)
     data2 = pop(lint2) -> data;
    else
     data2 = 0;
    
    value = data1 + data2 + carry;
    carry = value / 10000;
    if(carry)
     value = value - carry * 10000;
    push(result,value);
    len--;
   }

 cout << endl << endl;
 reverse(&result); //reverse result
 cout << "Result : ";
 display(result,carry); //display result

 getch();
 return 0;
}

Addition of Very Long Integers using Linked List

Posted by Unknown On 0 comments

/*****************************************************************
 APPLICATION : Addition of Very Long Integers (using Linked List)
 CODED BY    : Ankit Pokhrel
 COMPILED ON : Borland C++ Ver 5.02
 DATE     : 2010 - July - 02
******************************************************************/

#include "iostream.h"
#include "conio.h"
#include "stdlib.h"

struct List //Structure to represent a node
{
 int data;
 struct List *next,*head,*Top;
};

typedef List node;
node *New;

void initialize(node **n) //Function to initialize a Node
{
 (*n)  = new node;
 (*n) -> next = NULL;
 (*n) -> head = NULL;
 (*n) -> Top == NULL;
}

void create(int Item) //Function to create a node
{
 New = new node;
 New -> next = NULL;
 New -> data = Item;
}

void push(node *n,int Item) //Function to add data to stack
{
 if(n -> Top == NULL) //if first item
  {
   n -> data = Item;
   n -> head = n;
   n -> Top = n;
   return;
  }

 create(Item);
 n -> Top -> next = New;
 n -> Top = New;
}

int pop(node *n) //Function to delete item from node
{
 if(n -> Top == NULL) //if no data
   return -999;

 node *poped,*temp = n -> head;
 if(n -> Top == n -> head)
  {
   poped = n -> head;
   n -> Top = NULL;
   n -> head = NULL;
   return poped -> data;
  }

 while(temp -> next != n -> Top) //traverse to second last node
  temp = temp -> next;

 poped = n -> Top;
 temp -> next = NULL;
 n -> Top = temp;
 return poped -> data;
}

void display(node *n,int carry) //Function to display the items of stack
{
 if(n -> Top == NULL) //if no Items
  {
   cout << "Stack is Empty.";
   return;
  }

 int rev[100],i = 0;
 node *temp = n -> head;
 rev[i++] = temp -> data; //save data to array
 while(temp -> next != NULL)
  {
   temp = temp -> next;
   rev[i++] = temp -> data;
  }

 if(carry)
  cout << carry;
 for(int j = i-1;j >= 0;j--) //Display data in reverse order
  cout << rev[j];
}

int main()
{
 node *opr1,*opr2,*result;
 //Initalize all nodes
 initialize(&opr1);
 initialize(&opr2);
 initialize(&result);

 char oprand1[100],oprand2[100],ch[2];
 //Scan Inputs
 cout << "Enter Number : ";
 cin >> oprand1;
 int i = 0,value,len1,len2,len;
 oprand1[i-1] = ' ';
 while(oprand1[i] != '\0')
  {
   ch[0] = oprand1[i];
   ch[1] = '\0';
   value = atoi(ch);
   push(opr1,value);
   i++;
  }

 len1 = i;

 cout << "Enter Number : ";
 cin >> oprand2;

 i = 0;
 oprand2[i-1] = ' ';
 while(oprand2[i] != '\0')
  {
   ch[0] = oprand2[i];
   ch[1] = '\0';
   value = atoi(ch);
   push(opr2,value);
   i++;
  }

 len2 = i;

 if(len1 > len2)
  len = len1;
 else
  len = len2;
 
 int value1,value2,value3,carry = 0;
 while(len > 0) //while data on largest Stack
  {
   value1 = pop(opr1); //pop data
   if(value1 == -999) //if no data
    value1 = 0; //set value1 to zero
   value2 = pop(opr2); //pop data
   if(value2 == -999) //if no data
     value2 = 0; //set value2 to zero

   value3 = value1 + value2 + carry; //Add all data
   carry = value3/10; //Find Carry
   if(carry)
    value3 -= 10 * carry; //Remove Carry part

   push(result,value3); //push result to different stack
   len--;
  }

 cout << "\nResult : ";
 display(result,carry); //Display result
 getch();
 return 0;
}

Implementation of Linked List as a Phonebook

Posted by Unknown On Saturday, July 10, 2010 0 comments

#include "iostream.h"
#include "conio.h"
#include "string.h"
#include "iomanip.h"
#include "fstream.h"
#include "process.h"

const int TRUE = 1;
const int FALSE = 0;

struct phoneBook
{
 char name[15],addr[15],phone[12];
};

struct Linked_List
{
 struct phoneBook ph;
 struct Linked_List *next;
};

typedef struct Linked_List node;

node *head = NULL,*New;

void initialize(node *N)
{
 cout << "\n\t\t\tName : ";
 cin >> N -> ph.name;
 cout << "\n\t\t\tAddress : ";
 cin >> N -> ph.addr;
 cout << "\n\t\t\tPhone No. : ";
 cin >> N -> ph.phone;
}

int empty(node *n)
{
 if(strcmp(n -> ph.name,"") == 0 && strcmp(n -> ph.addr,"") == 0 && strcmp(n -> ph.name,"") == 0)
  return 1;
 else
  return 0;
}

void create()
{
 New = new node;
 strcpy(New -> ph.name,"");
 strcpy(New -> ph.addr,"");
 strcpy(New -> ph.phone,"");
 New -> next = NULL;
 if(head == NULL)
  head = New;
}

int insert()
{
 ofstream outfile;
 outfile.open("d:\\Dbase.txt",ios::app);
 if(outfile.fail())
  {
   cout << "Error : Couldn't open file.";
   getch();
   exit(0);
  }

 if(head == NULL)
  create();

 if(head -> next == NULL)
  if(empty(head))
     {
   initialize(New);
      outfile.write((char *) &head,sizeof(head));
      return 1;
     }

 char ntmp[15];
 create();
 initialize(New);
 strcpy(ntmp,New -> ph.name);
 node *temp = head,*loc = head;
 if(strcmpi(ntmp,head -> ph.name) < 0)
 {
   New -> next = head;
   head = New;
 }

 else
  {
    while(temp -> next != NULL)
     {
       temp = temp -> next;
       if(strcmpi(ntmp,temp -> ph.name) > 0)
       loc = temp;
      }

    New -> next = loc -> next;
    loc -> next = New;
   }
 return 1;
}

void search(char *n)
{
 node *temp = head;
 int found = FALSE;

 if(head == NULL)
   found = FALSE;

 else if(strcmp(n,temp -> ph.name) == 0)
  found = TRUE;

 else
 {
  while(temp -> next != NULL)
  {
    temp = temp -> next;
    if(strcmp(n,temp -> ph.name) == 0)
     {
       found = TRUE;
       break;
      }
   }
  }

 if(found)
  {
    cout << "\n\n\t\t  Name : " << temp -> ph.name;
    cout << "\n\t\t  Address : " << temp -> ph.addr;
    cout << "\n\t\t  Phone NO. : " << temp -> ph.phone;
   }

 else
  {
    cout << "\n\n" << setw(44) << "Data not found";
    cout << "\n" << setw(53) << "Press any key to continue...";
   }
}


int remove(char *n)
{
 if(head == NULL)
    return 0;

 node *temp = head,*loc = head;
 if(strcmp(n,temp -> ph.name) == 0)
    {
     if(temp -> next == NULL)
       {
        head = NULL;
        delete temp;
       }

     else
       {
        head = temp -> next;
        delete temp;
       }
     return 1;
      }

 else
  {
    while(temp -> next != NULL)
     {
       temp = temp -> next;
       if(temp == NULL)
       return 0;

       if(strcmpi(n,temp -> ph.name) == 0)
        {
       if(temp -> next != NULL)
          {
            temp = loc -> next;
     loc -> next = temp -> next;
     delete temp;
          }
         else
           loc -> next = NULL;

         return 1;
        }

       loc = loc -> next;
      }
  }
 return 0;
}

int modify(char *n)
{
 node *temp = head;
 if(head == NULL)
  return 0;
  
 if(strcmpi(n,temp -> ph.name) == 0)
  {
    cout << "\n\n\t\t\t***** Previous Data *****";
    cout << "\n\t\t\t  Name : " << temp -> ph.name;
    cout << "\n\t\t\t  Address : " << temp -> ph.addr;
    cout << "\n\t\t\t  Phone NO. : " << temp -> ph.phone;
    cout << "\n\n\t\t\t***** Enter New Data *****\n";
    initialize(head);
    return 1;
   }

 else
 {
  while(temp -> next != NULL)
  {
    temp = temp -> next;
    if(temp == NULL)
     return 0;

    if(strcmpi(n,temp -> ph.name) == 0)
     {
       cout << "\n\n\t\t\t***** Previous Data *****";
       cout << "\n\t\t\t  Name : " << temp -> ph.name;
   cout << "\n\t\t\t  Address : " << temp -> ph.addr;
     cout << "\n\t\t\t  Phone NO. : " << temp -> ph.phone;
       cout << "\n\n\t\t\t***** Enter New Data *****\n";
  initialize(temp);
  return 1;
      }
    }
  }
 return 0;
}

void display()
{
 node *temp = head;
 if(head == NULL)
  {
   cout << "\n\n" << setw(46) << "Database is empty";
   cout << "\n" << setw(53) << "Press any key to continue...";
   return;
  }

 if(!empty(head))
  {
   cout << "\n\n\t\t  Name : " << temp -> ph.name;
   cout << "\n\t\t  Address : " << temp -> ph.addr;
   cout << "\n\t\t  Phone NO. : " << temp -> ph.phone << endl << endl;
  }

 while(temp -> next != NULL)
  {
    temp = temp -> next;
    cout << "\n\t\t  Name : " << temp -> ph.name;
  cout << "\n\t\t  Address : " << temp -> ph.addr;
  cout << "\n\t\t  Phone NO. : " << temp -> ph.phone << endl;
   }
}

int menu()
{
 cout << "\n\t\t      **********************************" << endl;
 cout << "\t\t      *     ----------------------     *" << endl;
 cout << "\t\t      *        TELEPHONE DIARY         *" << endl;
 cout << "\t\t      *     ----------------------     *" << endl;
 cout << "\t\t      **********************************" << endl << endl;
 cout << "\t\t      -----------------------------------" << endl;
 cout << "\t\t\t1. Add\n";
 cout << "\t\t\t2. Search\n";
 cout << "\t\t\t3. Delete\n";
 cout << "\t\t\t4. Modify\n";
 cout << "\t\t\t5. View\n";
 cout << "\t\t\t0. Exit\n";
 cout << "\t\t      -----------------------------------" << endl << endl;

 int choice;
 cout << setw(45) << "Enter Choice : ";
 cin >> choice;
 return choice;
}

int main()
{
 char name[15];
  do
 {
  clrscr();
  int choice = menu();
  int success;
  cout << "\n\t\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
  switch(choice)
   {
    case 1:
     success = insert();
         if(success)
            cout << "\n\n\n" << setw(51) << "Data Inserted Successfully";

         cout << "\n" << setw(53) << "Press any key to continue...";
         break;

    case 2:
     cout << "\n\t\t\tEnter Name : ";
         cin >> name;
     search(name);
     break;

    case 3:
     cout << "\n\t\t\tEnter Name : ";
         cin >> name;
         success = remove(name);
         if(success)
           cout << "\n\n\n" << setw(50) << "Data Deleted Successfully";
         else
           cout << "\n\n" << setw(48) << "Data Doesn't Exists";

         cout << "\n" << setw(53) << "Press any key to continue...";
     break;

    case 4:
     cout << "\n\t\t\tEnter Name : ";
         cin >> name;
         success = modify(name);
         if(success)
           cout << "\n\n\n" << setw(50) << "Data Modified Successfully";
         else
           cout << "\n\n" << setw(48) << "Data Doesn't Exists";

         cout << "\n" << setw(53) << "Press any key to continue...";
     break;

    case 5:
     display();
         break;

    case 0:
     clrscr();
         cout << "\n\n\n\n\n\n\n\n";
         cout << setw(46) << "TELEPHONE DIARY\n";
         cout << setw(47) << "(Using Linked List)";
         cout << "\n\n" << setw(51) << "A Program by Ankit Pokhrel";
         cout << "\n\n\n\n\n" << setw(51) << "Press any key to halt...";
         getch();
     return 0;

    default:
         cout << endl << setw(58) << "Please select appropriate option\n";
         cout << setw(55) << "Press any key to continue...";
   }

  getch();
 }while(1);
}


The Josephus Problem

Posted by Unknown On 1 comments

/********************************************************
The Josephus Problem

--> The Problem is known as the Josephus problem and postulates a group of
soldiers surrounded by an overwhelming enemy force. There is no hope for
victory without reinforcements, but there is only a single horse available
for escape and summon help. They form a circle and a number n is picked from
Circurlar linked listImage via Wikipedia
Fig: Circular Linked List
a hat. One  of their names is also picked from a hat. Beginning with the
soldier whose name is picked, they begin to count clockwise around the circle.
when the count reaches n, that soldier is removed from the circle, and the
count reaches n, another soldier is removed from the circle. Any soldier
removed from the circle is no longer counted. The last soldier remaining is to
take the horse and escape.
The problem is, given a number n, the ordering of the soldiers in the
circle, and the soldier from whom the count begins, to determine the order in
which soldiers are eliminated from the cirlce and which soldier escapes.
*********************************************************/

/*******************************************************
 APPLICATION : The Josephus Problem
 CODED BY    : Ankit Pokhrel
 COMPILED ON : Borland C++ Ver 5.02
 DATE     : 2010 - July - 01
********************************************************/

#include "iostream.h"
#include "conio.h"
#include "string.h"

struct Josephus
{
 char name[15];
 struct Josephus *next;
};

typedef Josephus node;

node *New,*head = NULL,*ptr;

void create(char *n) //Function to create node and link
{
 New = new node;
 strcpy(New -> name,n);
 if(head == NULL)
  {
  head = New;
   head -> next = head;
   ptr = head;
  }

 else
  {
    ptr -> next = New;
    New -> next = head;
    ptr = New;
   }
}

node* remove(char *n) //Function to delete a node
{
 node *temp = head,*deleted;
 while(strcmp(temp -> next -> name,n) != 0)
   temp = temp -> next;

 deleted = temp -> next;
 temp -> next = temp -> next -> next;
 return deleted; //return deleted node
}

int main()
{
 create(""); //Create first node with empty contents to represent end or Start of list
 int m,n,i,j;
 char nme[15],sname[15];
 do
 {
  cout << "How many Soldiers? "; //Scan total number of soldiers
  cin >> m;
  if(m <= 0)
   cout << "\nPlease choose number greater than " << m << endl;
 }while(m <= 0);

 do
 {
  cout << "\nEnter N = "; //Scan N
  cin >> n;
  if(n <= 0)
  cout << "\nPlease pick the number greater than " << m;
 }while(n <= 0);

 for(i = 0;i < m;i++) //Scan Soldiers Name
  {
   cout << "\nEnter Name : ";
   cin >> nme;
  create(nme); //Create a list of soldiers
  }

 cout << "\n\nStart With : "; //Starting Soldier
 cin >> sname;

 node *temp = head,*nd;
 while(strcmp(temp -> next -> name,sname) != 0)
  {
  temp = temp -> next; //Go to starting soldier
   if(strcmp(temp -> name,"") == 0) //if not found
    {
     cout << "\nSorry, the Soldier is not on list";
     getch();
     return 0;
    }
  }

 cout << endl << endl;
 for(int k = 0;k < m;k++)
  {
   j = 0;
   for(i = 1;i <= n;i++) //Loop from 1 to n
   {
    temp = temp -> next; //Move to next node
    j++;
    if(strcmp(temp -> name,"") == 0) //Ignore empty node
     {
      j--;
      i--;
     }

    if(j == n) //If node is found
     {
      nd = remove(temp -> name); //Remove node
      if(k != m-1) //If more than one node
       cout << "Eliminated Soldier : " << nd -> name << endl;

      else
         cout << "\nThe Soldier to take Horse and Escape is " << nd -> name << endl;

      break; //Exit from loop
     }
  }
 }

 getch();
 return 0;
}

Enhanced by Zemanta

Queue Implementation of Linked List

Posted by Unknown On 0 comments

/*******************************************************
 APPLICATION : Queue Implementation of Linked List
 CODED BY    : Ankit Pokhrel
 COMPILED ON : Borland C++ Ver 5.02
 DATE     : 2010 - June - 29
********************************************************/

#include "iostream.h"
#include "conio.h"
#include "process.h"

struct Queue //Structure to represent Queue
{
 int data;
 struct Queue *next,*front,*rear,*head; //Pointers to next node,head,front and rear
};

typedef struct Queue node; //Now, node represent Structure Queue

node *New; //Global Variable to represent node

void initialize(node *n)
{
 n -> next = n -> head = n -> front = n -> rear = NULL;
}

void create(node *n)
{
 New = new node; //Create a new node
 New -> data = NULL; //Initialize data
 New -> next = NULL; //Initialize next pointer field
 if(n -> head == NULL) //if first node
  n -> head = New; //Initialize head
}

void QINSERT(node *n,int ITEM)
{
 node *temp = n -> head;
 create(n); //Create a Node
 New -> data = ITEM; //Insert Item
 if(n -> front == NULL && n -> rear == NULL) //If first node
  n -> front = n -> rear = New; //front = rear = 1

 else
  {
   while(temp -> next != n -> rear -> next) //move to last node
   temp = temp -> next;

   temp -> next = New; //Last node points to new node
   n -> rear = New; //Now, rear is New node
  }
}

node* QDELETE(node *n)
{
 if(n -> head == NULL) //If the Queue is Empty
  {
    cout << "\nQueue Underflow";
    exit(0); //Exit from Program
   }

 node *deleted = n -> front;
 if(n -> front == n -> rear) //If only one element
  {
   n -> head = NULL;
  n -> front = n -> rear = NULL;
  }

 else
  n -> front = n -> front -> next; // Move to next node

 return deleted; //Return Deleted Node
}

void display(node *n)
{
 if(n -> head == NULL) //if no items
  {
    cout << "Queue is Empty";
    return;
   }

 node *temp = n -> front;
 cout << temp -> data << ' '; //Print First Item
 while(temp -> next != NULL)
  {
    temp = temp -> next; //Move to next node
    cout << temp -> data << ' '; //Print Next Item
   }
}

int main()
{
 int i,count = 5;
 node *list1 = new node,*list2 = new node,*list3 = new node;
 //Initialize all lists to avoid errors
 initialize(list1);
 initialize(list2);
 initialize(list3);
 cout << "Elements of First Queue : ";
 for(i = 1;i <= count;i++)
  QINSERT(list1,5*i); //Push 5 elements on Queue
 display(list1); //Display Elements of First List

 cout << "\n\nElements of Second Queue : ";
 for(i = 1;i <= count;i++)
  QINSERT(list2,7*i); //Push 5 elements on Queue
 display(list2); //Display Elements of Second List

 QINSERT(list3,(QDELETE(list1) -> data + QDELETE(list2) -> data)); //Add Elements of First Node and save to Third List
 i = 1; //Starts from 1 because first node is already processed
 while(i < count)
 {
  QINSERT(list3,(QDELETE(list1) -> data + QDELETE(list2) -> data)); //Add Elements
  i++;
 }

 cout << "\n\nElements of Third Queue (After Addition) : ";
 display(list3);

 getch();
 return 0;
}


Stack Implementation of Linked List

Posted by Unknown On 0 comments

/*******************************************************
APPLICATION : Stack Implementation of Linked List
CODED BY : Ankit Pokhrel
COMPILED ON : Borland C++ Ver 5.02
DATE : 2010 - June - 29
********************************************************/

#include "iostream.h"
#include "conio.h"
#include "process.h"

struct Stack //Structure to represent Stack
{
int data;
struct Stack *next; //Pointer to next node
};

typedef struct Stack node; //Now, node represent Structure Stack

node *New,*head = NULL,*top = NULL; //Global Variables

void create()
{
New = new node; //Create a new node
New -> data = NULL; //Initialize data
New -> next = NULL; //Initialize next pointer field
if(head == NULL) //if first node
{
head = New; //Initialize head
top = New; //Update top
}
}

void push(int ITEM)
{
node *temp = head;
if(head == NULL) //if First Item is Pushed to Stack
{
create(); //Create a Node
head -> data = ITEM; //Insert Item to head of List
return; //Exit from Function
}

create(); //Create a new Node
New -> data = ITEM; //Insert Item
while(temp -> next != NULL)
temp = temp -> next; //Go to Last Node

temp -> next = New; //Point New node
top = New; //Update top
}

node* pop()
{
node *temp = head,*deleted;
if(top == NULL) //If the Stack is Empty
{
cout << "\nStack Underflow"; exit(0); //Exit from Program } if(top == head) //If only one Item { deleted = head; head = top = NULL; //Set head and top to Null return deleted; //Return deleted node } while(temp -> next != top)
temp = temp -> next; //move pointer temp to second last node

temp -> next = NULL; //Second last node points to NULL
deleted = top; //Save topmost node
top = temp; //Update top
return deleted; //Return deleted node
}

void display()
{
if(head == NULL) //if no items
{
cout << "Stack is empty"; return; } node *temp = head; cout << temp -> data << ' '; //Print First Item while(temp -> next != NULL)
{
temp = temp -> next; //Move to next node
cout << temp -> data << ' '; //Print Next Item } } int main() { node *n; int i; for(i = 1;i <= 5;i++) push(5*i); //Push 5 elements on Stack cout << "The elements of Stack are : "; display(); //Display all Elements for(i = 1;i <= 5;i++) { n = pop(); //Pop elements cout << endl << "\nDeleted Item : " << n -> data << endl; //Display deleted element
cout << "The elements of Stack are : ";
display(); //Display all Elements
}

cout << "\n\nThis is Stack Underflow Condition (No Items on Stack).";
getch();
n = pop(); //Stack Underflow Condition (no Items on Stack)
return 0;
}

Doubly Linked LIst

Posted by Unknown On 0 comments

#include "iostream.h"
#include "conio.h"

struct node
{
 int info;
 struct node *rptr,*lptr;
}*New,*head = NULL;

void create(int ITEM)
{
 New = new node;
 New -> info = ITEM;
 New -> lptr = NULL;
 New -> rptr = NULL;
 if(head == NULL)
  head = New;
}

void insert(int ITEM,int loc)
{
 create(ITEM);
 struct node *locPtr,*temp;
 if(loc <= 0)
  {
    cout << "Invalid Location";
    getch();
    return;
   }

 if(loc == 1)
  {
    New -> rptr = head;
    head -> lptr = New;
    head = New;
   }

 else
  {
    locPtr = head;
    for(int i = 2;i < loc;i++)
     {
       locPtr = locPtr -> rptr;
       if(locPtr == NULL)
       {
          cout << "Invalid Location";
          getch();
          return;
         }
       }

      temp = locPtr -> rptr;
      locPtr -> rptr = New;
      New -> lptr = locPtr;
      New -> rptr = temp;
      temp -> lptr = New;
   }
}

void remove(int loc)
{
 struct node *locPtr = head,*temp;
 if(loc <= 0)
  {
    cout << "Invalid Location.";
    getch();
    return;
   }

 if(loc == 1)
  {
    head = head -> rptr;
    delete head;
   }

 else
  {
   for(int i = 2;i < loc;i++)
   {
       locPtr = locPtr -> rptr;
       if(locPtr == NULL)
       {
          cout << "Invalid Location";
          getch();
          return;
         }
       }

   temp = locPtr -> rptr;
   locPtr -> rptr = temp -> rptr;
   delete temp;
   temp = temp -> rptr;
   temp -> lptr = locPtr;
  }
}

void display()
{
 struct node *temp = head;
 cout << temp -> info << ' ';
 while(temp -> rptr != NULL)
  {
    temp = temp -> rptr;
    cout << temp -> info << ' ';
   }
}

void displayBack()
{
 struct node *temp = head;
 while(temp -> rptr != NULL)
    temp = temp -> rptr;

 cout << temp -> info << ' ';
 while(temp -> lptr != NULL)
  {
    temp = temp -> lptr;
    cout << temp -> info << ' ';
   }
}

int main()
{
 create(0);
 for(int i = 1;i <= 5;i++)
  insert(6*i,i);

 display();
 cout << endl;
 displayBack();
 remove(3);
 cout << endl << endl;
 display();
 getch();
 return 0;
}

Singly Linked List

Posted by Unknown On 0 comments

/********* Singly Linked List **********/

#include "iostream.h"
#include "conio.h"

Single linked listFig: Singly Linked List
struct Linked_List //Structure to Represent Linked List
{
 int info;
 struct Linked_List *next,*head;
};

typedef Linked_List list; //Now list represent Linked List

list *New; //Global Variable of type list

void create(int ITEM) //Function to create a node of a list
{
 New = new list; //create a node
 New -> info = ITEM; //insert Item
 New -> next = NULL; //Assign next to NULL
}

void insert(int ITEM,int loc,list *&lst) //Function to insert Item on list
{
 if(loc <= 0) //Location must start from 1
  {
   cout << "\nInvalid Location";
Diagram of inserting a node into a singly link...Fig : Insertion on a Linked List
   getch();
   return; //Exit from Function
  }

 if(loc == 1)
  {
   if(lst == NULL) //If List Doesn't Exist
    {
     lst = new list; //Create a list
     lst -> info = ITEM; //Copy Item to Node
     lst -> next = NULL; //Assign next to NULL1
     lst -> head = lst; //Update Head
    }

   else
    {
     create(ITEM); //Create a Node
     New -> next = lst -> head; //Link New node at First of head
     lst -> head = New; //Update Head of List
     lst = lst -> head;
    }
  }

 else
  {
   list *lptr = lst -> head; //Start from beginning of List
   for(int i = 2;i < loc;i++) //From Second node to seconlast node
    {
     lptr = lptr -> next; //Move the Pointer
     if(lptr == NULL)
      {
       cout << "\nInvalid Location";
       getch();
       return;
      }
    }

  create(ITEM); //Create a Node
  New -> next = lptr -> next; //Update next of New Node
  lptr -> next = New; //Assign New to next of lptr
 }
}

/*
Function to remove a node
 1. From Beginning
 2. Inbetween 2 Nodes
*/

list* remove(int ITEM,list *&lst)
{
 list *lptr = lst,*loc,*deleted;
 if(lptr -> info == ITEM) //If first item to be Deleted
  {
   lst = lst -> next; //Move lst
   lst -> head = lst; //Update head
   return lptr; //return deleted Node
  }

 //Find Item
  loc = lptr;
Diagram of deleting a node from a singly linke...Fig : Deletion of a Node
  lptr = lptr -> next;
  while(lptr -> next != NULL)
   {
    loc = lptr;
    lptr = lptr -> next; //Move lptr
    if(lptr -> info == ITEM) //if Item is found
     break; //Break from Loop
    loc = NULL; //Item not Found
   }

 if(loc != NULL) //if Item found
 {
  //delete Item
  deleted = loc -> next;
  loc -> next = loc -> next -> next;
  return deleted; //return Deleted
 }

 else
  return NULL; //Item not Found
}

void display(list *lst) //Function to Display elements of List
{
 list *temp = lst;
 cout << temp -> info << ' '; //Print First Item
 while(temp -> next != NULL) //Until Last
  {
    temp = temp -> next; //Move temp
    cout << temp -> info << ' '; //Print Item
   }
}

int main()
{
 list *l = NULL,*temp;
 int n = 0,i = 1;
 cout << "Enter Numbers\n";
 cout << "Input -999 to Stop\n";
 while(n != -999) //scan Input until user enters -999
  {
   cin >> n;
   if(n != -999)
  insert(n,i++,l); //insert Item on List
  }

 cout << endl << "List Created : ";
 display(l); //display List l
 cout << endl << endl;

 cout << "Delete : ";
 cin >> n;
 temp = remove(n,l); //Delete Node from List l
 if(temp != NULL)
  {
   cout << "\nDeleted : " << temp -> info << endl; //Print Deleted Node
   cout << "Data on List : ";
   display(l); //Print Current Elements of List
  }

 else
  cout << "\nData Not Found";

 getch();
 return 0;
}

Enhanced by Zemanta

Leave Feedback about this BLOG