Vous êtes sur la page 1sur 26

/*******************************************************

* MYCPLUS Sample Code - http://www.mycplus.com *


* *
* This code is made available as a service to our *
* visitors and is provided strictly for the *
* purpose of illustration. *
* *
* Please direct all inquiries to saqib at mycplus.com *
*******************************************************/

/************************************************************************/
/* BASIC STACK OPERATIONS */
/************************************************************************/

#include <stdio.h>
#include<process.h>
#include <dos.h>
#include<conio.h>
#include<stdio.h>

#define SIZE 5

static struct stack{


int top;
int items[SIZE];
}s1;

void push(struct stack *,int);


int pop(struct stack*);
int stacktop(struct stack*);
int empty(struct stack*);
int search(struct stack *,int);
void insert(struct stack *,int,int);
void replace(struct stack *,int,int);
void del(struct stack *,int);
void printline(void);

void main()
{
char c;
int i,temp;
s1.top=-1;
mark:
clrscr();
gotoxy(28,2);
printf("BASIC STACK OPERATIONS");
gotoxy(34,4); printf("(1) Push");
gotoxy(34,6); printf("(2) Pop");
gotoxy(34,8); printf("(3) Search");
gotoxy(34,10); printf("(4) Insert");
gotoxy(34,12); printf("(5) Replace");
gotoxy(34,14); printf("(6) Delete\n\n");
gotoxy(0,18); printline();
c=getch();
switch (c)
{
case '1': printf("\nWhat element do you wish to push?");
scanf("%d",&temp);
push(&s1,temp);
break;
case '2': pop(&s1);
break;
case '3': printf("\nEnter the element you wish to search?");
scanf("%d",&temp);
printf("\nThe element is at index %d\n",search(&s1,temp));
break;
case '4': printf("\nEnter the POSTION and ELEMENT you wish to insert?");
scanf("%d %d",&i,&temp);
insert(&s1,i,temp);
break;
case '5': printf("\nEnter the POSTION and ELEMENT you wish to replace?");
scanf("%d %d",&i,&temp);
replace(&s1,i,temp);
break;
case '6': printf("\nEnter the POSTION you wish to delete from stack?");
scanf("%d",&temp);
del(&s1,temp);
break;
default : printf("\nInvalid entry! Try again!");
break;
}
for (i=s1.top;i>=0;i--)
printf("\nThe element at position (%d) is %4d",i,s1.items[i]);
printf("\n\nDo you wish to continue?");
c=getch();
if (c=='y')
goto mark;
}

void push(struct stack *sx,int x)


{
if (sx->top==SIZE-1)
{
printf("\n\tSTACT OVERFLOW\n");
getch();
exit(1);
}
sx->items[++sx->top]=x;
}

int pop(struct stack *sx)


{
if (empty(sx))
{
printf("\n\t STACK UNDERFLOW\n");
getch();
exit(1);
}
return(sx->items[sx->top--]);
}

int stacktop(struct stack *sx)


{
return(sx->items[sx->top]);
}

int empty(struct stack *sx)


{
return((sx->top==-1));
}

int search(struct stack *sx,int n)


{
int arr[20];
int i=0,j,result=-1;
for (j=sx->top;!(empty(sx));j--)
{
if (n==stacktop(sx))
{
result=sx->top;
break;
}
arr[i++]=pop(sx);
}
for (j=i-1;j>=0;j--)
push(sx,arr[j]);
return(result);
}

void insert(struct stack *sx,int pos,int ele)


{
int arr[20];
int i=0,j;
for (j=sx->top;j>=pos;j--)
arr[i++]=pop(sx);
push(sx,ele);
for (j=i-1;j>=0;j--)
push(sx,arr[j]);
}

void replace(struct stack *sx,int pos,int ele)


{
int arr[20];
int i=0,j;
for (j=sx->top;j>=pos;j--)
arr[i++]=pop(sx);
push(sx,ele);
for (j=i-2;j>=0;j--)
push(sx,arr[j]);
}

void del(struct stack *sx,int pos)


{
int arr[20];
int i=0,j;
for (j=sx->top;j>pos;j--)
arr[i++]=pop(sx);
pop(sx);
for (j=i-1;j>=0;j--)
push(sx,arr[j]);
}

void printline(void)
{
int i;
for (i=0;i<40;i++)
printf("®¯");
}
Stack implementation as a class.

# include<iostream.h>
# include<process.h>
# include<conio.h>
# define SIZE 20

class stack
{
int a[SIZE];
int tos; // Top of Stack
public:
stack();
void push(int);
int pop();
int isempty();
int isfull();
};
stack::stack()
{
tos=0; //Initialize Top of Stack
}

int stack::isempty()
{
return (tos==0?1:0);
}
int stack::isfull()
{
return (tos==SIZE?1:0);
}

void stack::push(int i)
{
if(!isfull())
{
a[tos]=i;
tos++;
}
else
{
cerr<<"Stack overflow error !
Possible Data Loss !";
}
}
int stack::pop()
{
if(!isempty())
{
return(a[--tos]);
}
else
{
cerr<<"Stack is empty! What to pop...!";
}
return 0;
}

void main()
{
stack s;
int ch=1,num;
while(ch!=0)
{
cout<<"Stack Operations Mani Menu
1.Push
2.Pop
3.IsEmpty
4.IsFull
0.Exit
<BR>;
cin>>ch;
switch(ch)
{
case 0:
exit(1); //Normal Termination of Program
case 1:
cout<<"Enter the number to push";
cin>>num;
s.push(num);
break;
case 2:
cout<<"Number popped from the stack is: "<<s.pop()<<endl;
break;
case 3:
(s.isempty())?(cout<<"Stack is empty.<BR>):(cout<<"Stack is not empty.<BR>);
break;
case 4:
(s.isfull())?(cout<<"Stack is full.<BR>):(cout<<"Stack is not full.<BR>);
break;
default:
cout<<"Illegal Option.
Please try again<BR>;
}
}//end of while
getch();
}

Implementing Stack using Class (with constructor etc).

# include<iostream.h>
# include<conio.h>
# define SIZE 20

class stack
{
int a[SIZE];
int tos; // Top of Stack
public:
stack();
void push(int);
int pop();
int isempty();
int isfull();
};
stack::stack()
{
tos=0; //Initialize Top of Stack
}

int stack::isempty()
{
return (tos==0?1:0);
}
int stack::isfull()
{
return (tos==SIZE?1:0);
}

void stack::push(int i)
{

if(!isfull())
{
cout<<"Pushing "<<i<<endl;
a[tos]=i;
tos++;
}
else
{
cerr<<"Stack overflow error !
Possible Data Loss !";
}
}
int stack::pop()
{
if(!isempty())
{
cout<<"Popping "<<a[tos-1]<<endl;
return(a[--tos]);
}
else
{
cerr<<"Stack is empty! What to pop...!";
}
return 0;
}

void reverse(stack s)
{
stack s2;
while(!s.isempty())
{
s2.push(s.pop());
}
cout<<"Reversed contents of the stack..."<<endl;
while(!s2.isempty())
{
cout<<s2.pop()<<endl;
}
}//end of fn.
void main()
{
clrscr();
stack s;
s.push(1);
s.push(2);
s.push(3);

reverse(s);
getch();
}

Implementing Queue as a Class

# include<iostream.h>
# include<conio.h>
# define SIZE 20

class queue
{
int a[SIZE];
int front;
int rear;
public:
queue();
~queue();
void insert(int i);
int remove();
int isempty();
int isfull();
};

queue::queue()
{
front=0;
rear=0;
}
queue::~queue()
{
delete []a;
}
void queue::insert(int i)
{
if(isfull())
{
cout<<"

******
Queue is FULL !!!
No insertion allowed further.
******<BR>;
return;
}
a[rear] = i;
rear++;
}
int queue::remove()
{
if(isempty())
{
cout<<"

******
Queue Empty !!!
Value returned will be garbage.
******<BR>;
return (-9999);
}

return(a[front++]);
}
int queue::isempty()
{
if(front == rear)
return 1;
else
return 0;
}
int queue::isfull()
{
if(rear == SIZE)
return 1;
else
return 0;
}

void main()
{
clrscr();
queue q;
q.insert(1);
q.insert(2);
cout<<"<BR><<q.remove();
cout<<"<BR><<q.remove();
cout<<"<BR><<q.remove();
getch();
}

Doubly linked lists

Description : Doubly linked lists


// Sorted Doubly Linked List with Insertion and Deletion

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

class Dllist
{
private:
typedef struct Node
{
string name;
Node* next;
Node* prev;
};
Node* head;
Node* last;
public:
Dllist()
{
head = NULL;
last = NULL;
}
bool empty() const { return head==NULL; }
friend ostream& operator<<(ostream& ,const Dllist& );
void Insert(const string& );
void Remove(const string& );
};

void Dllist::Insert(const string& s)


{
// Insertion into an Empty List.
if(empty())
{
Node* temp = new Node;
head = temp;
last = temp;
temp->prev = NULL;
temp->next = NULL;
temp->name = s;
}
else
{
Node* curr;
curr = head;
while( s>curr->name && curr->next != last->next) curr = curr->next;

if(curr == head)
{
Node* temp = new Node;
temp->name = s;
temp->prev = curr;
temp->next = NULL;
head->next = temp;
last = temp;
// cout<<" Inserted "<<s<<" After "<<curr->name<<endl;
}
else
{
if(curr == last && s>last->name)
{
last->next = new Node;
(last->next)->prev = last;
last = last->next;
last->next = NULL;
last->name = s;
// cout<<" Added "<<s<<" at the end "<<endl;
}
else
{
Node* temp = new Node;
temp->name = s;
temp->next = curr;
(curr->prev)->next = temp;
temp->prev = curr->prev;
curr->prev = temp;
// cout<<" Inserted "<<s<<" Before "<<curr->name<<endl;
}
}
}
}

ostream& operator<<(ostream& ostr, const Dllist& dl )


{
if(dl.empty()) ostr<<" The list is empty. "<<endl;
else
{
Dllist::Node* curr;
for(curr = dl.head; curr != dl.last->next; curr=curr->next)
ostr<<curr->name<<" ";
ostr<<endl;
ostr<<endl;
return ostr;
}
}

void Dllist::Remove(const string& s)


{
bool found = false;
if(empty())
{
cout<<" This is an empty list! "<<endl;
return;
}
else
{
Node* curr;
for(curr = head; curr != last->next; curr = curr->next)
{
if(curr->name == s)
{
found = true;
break;
}
}
if(found == false)
{
cout<<" The list does not contain specified Node"<<endl;
return;
}
else
{
// Curr points to the node to be removed.
if (curr == head && found)
{
if(curr->next != NULL)
{
head = curr->next;
delete curr;
return;
}
else
{
delete curr;
head = NULL;
last = NULL;
return;
}
}
if (curr == last && found)
{
last = curr->prev;
delete curr;
return;
}
(curr->prev)->next = curr->next;
(curr->next)->prev = curr->prev;
delete curr;
}
}
}

int main()
{
Dllist d1;
int ch;
string temp;
while(1)
{
cout<<endl;
cout<<" Doubly Linked List Operations "<<endl;
cout<<" ------------------------------"<<endl;
cout<<" 1. Insertion "<<endl;
cout<<" 2. Deletion "<<endl;
cout<<" 3. Display "<<endl;
cout<<" 4. Exit "<<endl;
cout<<" Enter your choice : ";
cin>>ch;
switch(ch)
{
case 1: cout<<" Enter Name to be inserted : ";
cin>>temp;
d1.Insert(temp);
break;
case 2: cout<<" Enter Name to be deleted : ";
cin>>temp;
d1.Remove(temp);
break;
case 3: cout<<" The List contains : ";
cout<<d1;
break;
case 4: system("pause");
return 0;
break;
}
}

// Abstract AVL Tree Template Test Suite.


// This code is in the public domain.
// Version: 1.5 Author: Walt Karas

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

#include "avl_tree.h"

// Check to make sure double inclusion OK.


#include "avl_tree.h"

void bail(const char *note)


{
printf("%s\n", note);
exit(1);
}

// Mask of highest bit in an unsigned int.


const unsigned HIGH_BIT = (~(((unsigned) (~ 0)) >> 1));
// Node array and "shadow" node array.
struct
{
signed char bf;

int val;

unsigned gt, lt;

}
arr[401], arr2[400];

// Class to pass to template as abstractor parameter.


class abstr
{
public:

// Handles are indexes into the "arr" array. If a handle has been
// "accessed", it has its high bit set. (The handle has to have been
// accessed in order to alter the node's values, or compare its key.)
typedef unsigned handle;

typedef unsigned size;

typedef int key;

static handle get_less(handle h, bool access)


{
if (!(h & HIGH_BIT))
bail("get_less");
handle child = arr[h & ~HIGH_BIT].lt;
if (access)
child |= HIGH_BIT;
return(child);
}

static void set_less(handle h, handle lh)


{
if (!(h & HIGH_BIT))
{
printf("%x %x\n", h, lh);
bail("set_less");
}
if (lh != ~0)
lh &= ~HIGH_BIT;
arr[h & ~HIGH_BIT].lt = lh;
}

static handle get_greater(handle h, bool access)


{
if (!(h & HIGH_BIT))
bail("get_greater");
handle child = arr[h & ~HIGH_BIT].gt;
if (access)
child |= HIGH_BIT;
return(child);
}

static void set_greater(handle h, handle gh)


{
if (!(h & HIGH_BIT))
bail("set_greater");
if (gh != ~0)
gh &= ~HIGH_BIT;
arr[h & ~HIGH_BIT].gt = gh;
}

static int get_balance_factor(handle h)


{
if (!(h & HIGH_BIT))
bail("get_balance_factor");
return(arr[h & ~HIGH_BIT].bf);
}

static void set_balance_factor(handle h, int bf)


{
if (!(h & HIGH_BIT))
bail("set_balance_factor");
arr[h & ~HIGH_BIT].bf = bf;
}

static int compare_key_node(key k, handle h)


{
if (!(h & HIGH_BIT))
bail("compare_key_node");
return(k - arr[h & ~HIGH_BIT].val);
}

static int compare_node_node(handle h1, handle h2)


{
if (!(h1 & HIGH_BIT))
bail("compare_node_node - h1");
if (!(h2 & HIGH_BIT))
bail("compare_node_node - h2");
return(arr[h1 & ~HIGH_BIT].val - arr[h2 & ~HIGH_BIT].val);
}

static handle null(void) { return(~0); }

static bool read_error(void) { return(false); }

};

// AVL tree with public root for testing purposes.


class t_avl_tree : public abstract_container::avl_tree<abstr>
{
public:
handle &pub_root;

t_avl_tree(void) : pub_root(abs.root) { }
};

t_avl_tree tree;

typedef t_avl_tree::iter iter;

// Verifies that a tree is a valid AVL Balanced Binary Search Tree.


// Returns depth. Don't use on an empty tree.
int verify_tree(unsigned subroot = tree.pub_root & ~HIGH_BIT)
{
int l_depth, g_depth;
unsigned h;

if (arr[subroot].lt == ~0)
l_depth = 0;
else
{
h = arr[subroot].lt & ~HIGH_BIT;
if (arr[subroot].val <= arr[h].val)
{
printf("not less: %u %d %d %d\n",
subroot, arr[subroot].val, h, arr[h].val);
bail("verify_tree");
}
l_depth = verify_tree(h);
}

if (arr[subroot].gt == ~0)
g_depth = 0;
else
{
h = arr[subroot].gt & ~HIGH_BIT;
if (arr[subroot].val >= arr[h].val)
{
printf("not greater: %u %d %d %d\n",
subroot, arr[subroot].val, h, arr[h].val);
bail("verify_tree");
}
g_depth = verify_tree(h);
}

if (arr[subroot].bf != (g_depth - l_depth))


{
printf("bad bf: n=%u bf=%d gd=%d ld=%d\n",
subroot, arr[subroot].bf, g_depth, l_depth);
bail("verify_tree");
}

return((g_depth > l_depth ? g_depth : l_depth) + 1);


}

void check_empty(void)
{
if (tree.pub_root != ~0)
bail("not empty");
}

void insert(unsigned h)
{
unsigned rh = tree.insert(h | HIGH_BIT);
if (rh == ~0)
bail("insert null");
rh &= ~HIGH_BIT;
if (arr[h].val != arr[rh].val)
{
printf("bad - %u %u\n", h, rh);
bail("insert");
}
}

void remove(int k, bool should_be_null = false)


{
unsigned rh = tree.remove(k);
if (rh == ~0)
{
if (!should_be_null)
{
printf("null key=%d\n", k);
bail("remove");
}
}
else
{
if (should_be_null)
{
printf("not null key=%d rh=%u\n", k, rh);
bail("remove");
}
rh &= ~HIGH_BIT;
if (arr[rh].val != k)
{
printf("wrong key=%d rh=%u [rh].val=%d\n", k, rh, arr[rh].val);
bail("remove");
}
// Mark balance factor of node to indicate it's not in the tree.
arr[rh].bf = 123;
}
}

unsigned max_elems;

// Prior to starting a test, mark all the nodes to be used in the test
// with a bad balance factor. This makes it easy to tell which nodes
// are in the tree and which aren't.
void mark_bf(void)
{
unsigned i = max_elems;

while (i)
{
i--;
arr[i].bf = 123;
}
}

void search_test(int key, abstract_container::search_type st, unsigned rh)


{
if (tree.search(key, st) != (rh | HIGH_BIT))
{
printf("%d %x %u\n", key, (unsigned) st, rh);
bail("search_test");
}
iter it;
it.start_iter(tree, key, st);
if (*it != (rh | HIGH_BIT))
{
printf("%d %x %x %x\n", key, (unsigned) st, rh, *it);
bail("search_test - iter");
}
if ((st == abstract_container::EQUAL) && (rh != ~0))
{
unsigned h = *it;
iter it2 = it;
it++;
it2--;
if (*it != tree.search(key, abstract_container::GREATER))
{
printf("%d %x %x %x\n", key, (unsigned) st, h, *it);
bail("search_test - iter ++");
}
if (*it2 != tree.search(key, abstract_container::LESS))
{
printf("%d %x %x %x\n", key, (unsigned) st, h, *it2);
bail("search_test - iter --");
}
}
return;
}

void search_test(unsigned h)
{

if (arr[h].bf == 123)
{
search_test(2 * h, abstract_container::EQUAL, ~0);

// Test subst function.


arr[400].val = 2 * h;
if (tree.subst(400 | HIGH_BIT) != ~0)
{
printf("max_elems=%u h=%x\n", max_elems, h);
bail("subst not there");
}
}
else
{
search_test(2 * h, abstract_container::EQUAL, h);
search_test(2 * h, abstract_container::LESS_EQUAL, h);
search_test(2 * h, abstract_container::GREATER_EQUAL, h);

search_test(2 * h + 1, abstract_container::EQUAL, ~0);


search_test(2 * h + 1, abstract_container::LESS, h);
search_test(2 * h + 1, abstract_container::LESS_EQUAL, h);

search_test(2 * h - 1, abstract_container::EQUAL, ~0);


search_test(2 * h - 1, abstract_container::GREATER, h);
search_test(2 * h - 1, abstract_container::GREATER_EQUAL, h);

// Test subst function.


arr[400].val = 2 * h - 1;
if (tree.subst(400 | HIGH_BIT) != ~0)
{
printf("max_elems=%u h=%x\n", max_elems, h);
bail("subst low");
}
arr[400].val = 2 * h;
if (tree.subst(400 | HIGH_BIT) != (h | HIGH_BIT))
{
printf("max_elems=%u h=%x\n", max_elems, h);
bail("subst in");
}
verify_tree();
if (tree.subst(h | HIGH_BIT) != (400 | HIGH_BIT))
{
printf("max_elems=%u h=%x\n", max_elems, h);
bail("subst out");
}
arr[400].val = 2 * h + 1;
if (tree.subst(400 | HIGH_BIT) != ~0)
{
printf("max_elems=%u h=%x\n", max_elems, h);
bail("subst high");
}
}
}

void search_all(void)
{
unsigned h = max_elems, min = ~0, max = ~0;

while (h)
{
h--;

search_test(h);

if (arr[h].bf != 123)
{
if (max == ~0)
max = h;
min = h;
}
}

h = tree.search_least();
if (h != (min | HIGH_BIT))
{
printf("%x %x\n", h, min);
bail("search_all least");
}

h = tree.search_greatest();
if (h != (max | HIGH_BIT))
{
printf("%x %x\n", h, max);
bail("search_all greatest");
}

iter it;

// Test forward iteration through entire tree.


it.start_iter_least(tree);
if (*it != (min | HIGH_BIT))
{
printf("%x %x\n", h, min);
bail("search_all least - iter");
}
while (*it != (max | HIGH_BIT))
{
h = *it;
it++;
if (*it != tree.search(2 * h, abstract_container::GREATER))
{
printf("%x %x\n", h, *it);
bail("search_all increment - iter");
}
}
it++;
if (*it != ~0)
bail("search_all increment - end");

// Test backward iteration through entire tree.


it.start_iter_greatest(tree);
if (*it != (max | HIGH_BIT))
{
printf("%x %x\n", h, max);
bail("search_all greatest - iter");
}
while (*it != (min | HIGH_BIT))
{
h = *it;
it--;
if (*it != tree.search(2 * h, abstract_container::LESS))
{
printf("%x %x\n", h, *it);
bail("search_all increment - iter");
}
}
it--;
if (*it != ~0)
bail("search_all increment - end");
}

void dump(unsigned subroot, unsigned depth)


{
if (arr[subroot].lt != ~0)
dump(arr[subroot].lt, depth + 1);
printf("%u(%u, %d) ", subroot, depth, arr[subroot].bf);
if (arr[subroot].gt != ~0)
dump(arr[subroot].gt, depth + 1);
}

void dump(void)
{
dump(tree.pub_root & ~HIGH_BIT, 0);
putchar('\n');
}

// Create a tree with the nodes whose handles go from 0 to max_elems - 1.


// Insert step and remove step parameters must be relatively prime to
// max_elems.
void big_test(unsigned in_step, unsigned rm_step)
{
unsigned in = 0, rm = 0;

printf("inserting\n");
do
{
insert(in);
verify_tree();
in += in_step;
in %= max_elems;
}
while (in != 0);

search_all();

printf("removing\n");
for ( ; ; )
{
remove(rm * 2);
rm += rm_step;
rm %= max_elems;
if (rm == 0)
break;
verify_tree();
}

check_empty();
}
// Iterate through all the possible topologies of AVL trees with a
// certain depth. The trees are created in the "shadow" node array,
// then copied into the main node array.
class possible_trees
{
private:

// 1-base depth.
unsigned depth_;

// Subtree description structure. size is number of nodes in subtree.


struct sub { unsigned root, size; };

sub t;

// Create "first" subtree of a given depth with the node whose handle
// is "start" as the node with the minimum key in the tree. balance
// factors of nodes with children are all -1 in the first subtree.
sub first(unsigned start, unsigned depth)
{
sub s;

if (depth == 0)
{
s.size = 0;
s.root = ~0;
}
else if (depth == 1)
{
arr2[start].bf = 0;
arr2[start].lt = ~0;
arr2[start].gt = ~0;
s.size = 1;
s.root = start;
}
else
{
s = first(start, depth - 1);
start += s.size;
arr2[start].bf = -1;
arr2[start].lt = s.root;
sub s2 = first(start + 1, depth - 2);
arr2[start].gt = s2.root;
s.root = start;
s.size += s2.size + 1;
}
return(s);
}

// If there is no "next" subtree, returns a subtree description with


// a size of zero.
sub next(unsigned start, unsigned subroot, unsigned depth)
{
sub s;

if (depth < 2)
// For a subtree of depth 1 (1 node), the first topology is the
// only topology, so no next.
s.size = 0;
else
{
// Get next greater subtree.
s = next(subroot + 1, arr2[subroot].gt,
depth - (arr2[subroot].bf == -1 ? 2 : 1));
if (s.size != 0)
{
arr2[subroot].gt = s.root;
s.size += subroot - start + 1;
s.root = subroot;
}
else
{
// No next greater subtree. Get next less subtree, and
// start over with first greater subtree.
int bf = arr2[subroot].bf;
s = next(start, arr2[subroot].lt, depth - (bf == 1 ? 2 : 1));
if (s.size == 0)
{
// No next less subtree.
if (bf == 1)
// No next balance factor.
return(s);
// Go to next balance factor, then start iteration
// all over with first less and first greater subtrees.
bf++;
s = first(start, depth - (bf == 1 ? 2 : 1));
}
start += s.size;
arr2[start].lt = s.root;
s.root = start;
sub s2 = first(s.root + 1, depth - (bf == -1 ? 2 : 1));
arr2[s.root].gt = s2.root;
arr2[s.root].bf = bf;
s.size += s2.size + 1;
}
}

return(s);
}

void dump(unsigned subroot, unsigned depth)


{
if (arr2[subroot].lt != ~0)
dump(arr2[subroot].lt, depth + 1);
printf("%u(%u, %d) ", subroot, depth, arr2[subroot].bf);
if (arr2[subroot].gt != ~0)
dump(arr2[subroot].gt, depth + 1);
}

public:

// Copy from shadow node array to main node array and set tree root.
void place(void)
{
memcpy(arr, arr2, t.size * sizeof(arr[0]));
tree.pub_root = t.root | HIGH_BIT;
}

void first(unsigned d) { depth_ = d; t = first(0, depth_); }

bool next(void)
{
if (t.size == 0)
bail("possible_trees::next");
t = next(0, t.root, depth_);
return(t.size > 0);
}

void dump(void) { dump(t.root, 0); putchar('\n'); }

possible_trees(void) { t.size = 0; }

};

possible_trees pt;

// Tests for each tree in the iteration.


void one_tree(void)
{
pt.place();
unsigned h = tree.search_least();
while (h != ~0)
{
arr[400].val = 2 * h - 1;
insert(400);
verify_tree();
pt.place();

arr[400].val = 2 * h + 1;
insert(400);
verify_tree();
pt.place();

remove(2 * h);
verify_tree();
pt.place();

h = tree.search(2 * h, abstract_container::GREATER);
}
}

void all_trees(unsigned depth)


{
pt.first(depth);
do
one_tree();
while (pt.next());
}

// Array of handles in order by node key.


unsigned h_arr[400];

// Test the build member function template by building tress with from 1
// to 400 nodes.
void build_test(void)
{
unsigned i;

tree.build(h_arr, 0);
check_empty();

for (i = 0; i < 400; i++)


{
h_arr[i] = i | HIGH_BIT;
tree.build(h_arr, i + 1);
verify_tree();
}
}
int main()
{
unsigned i;

printf(
"Empty member optimization is%s working\n",
sizeof(abstract_container::avl_tree<abstr>) == sizeof(unsigned) ?
"" : " NOT");

for (i = 0; i < 400; i++)


arr2[i].val = i * 2;

memcpy(arr, arr2, sizeof(arr));

max_elems = 3;
mark_bf();

printf("0 nodes\n");

check_empty();

search_all();

printf("1 node\n");

insert(1);
insert(1);
verify_tree();
search_all();
remove(2);
remove(2, true);
check_empty();

printf("2 nodes less slant\n");

insert(2);
insert(2);
insert(1);
insert(1);
verify_tree();
search_all();
remove(2);
remove(2, true);
insert(1);
verify_tree();
remove(4);
remove(4, true);
verify_tree();
remove(2);
check_empty();

printf("2 nodes greater slant\n");

insert(1);
insert(1);
insert(2);
insert(2);
verify_tree();
search_all();
remove(4);
remove(4, true);
insert(2);
verify_tree();
remove(2);
remove(2, true);
verify_tree();
remove(4);
check_empty();

max_elems = 400;

printf("%u nodes\n", max_elems);

mark_bf();

big_test(3, 7);
big_test(13, 7);

printf("all trees depth 3\n");

all_trees(3);

printf("all trees depth 4\n");

all_trees(4);

printf("all trees depth 5\n");

all_trees(5);

printf("build test\n");

build_test();

printf("SUCCESS!\n");

return(0);
}

stack
1. #include <iostream>  
2.   
3. using namespace std;  
4.   
5. #define MAX 10        // MAXIMUM STACK CONTENT  
6.   
7.   
8. class stack  
9. {  
10.   
11.   private:  
12.     int arr[MAX];   // Contains all the Data  
13.     int top;        //Contains location of Topmost Data pushed onto Stack  
14.   
15.   public:  
16.      stack()         //Constructor  
17.      {  
18.         top=-1;      //Sets the Top Location to -1 indicating an empty stack  
19.      }  
20.   
21.      void push(int a)  // Push ie. Add Value Function  
22.      {  
23.         top++;        // increment to by 1  
24.         if(top<MAX)  
25.          {  
26.             arr[top]=a;  //If Stack is Vacant store Value in Array  
27.          }  
28.          else  
29.          {  
30.             cout<<"STACK FULL!!"<<endl;  
31.             top--;  
32.          }  
33.      }  
34.   
35.     int pop()                  // Delete Item. Returns the deleted item  
36.     {  
37.         if(top==-1)  
38.         {  
39.             cout<<"STACK IS EMPTY!!!"<<endl;  
40.             return NULL;  
41.         }  
42.         else  
43.         {  
44.             int data=arr[top];     //Set Topmost Value in data  
45.             arr[top]=NULL;       //Set Original Location to NULL  
46.             top--;               // Decrement top by 1  
47.             return data;         // Return deleted item  
48.         }  
49.      }  
50. };  
51.   
52.   
53. int main()  
54. {  
55.  stack a;  
56.  a.push(3);  
57.  cout<<"3 is Pushed\n";  
58.  a.push(10);  
59.  cout<<"10 is Pushed\n";  
60.  a.push(1);  
61.  cout<<"1 is Pushed\n\n";  
62.   
63.  cout<<a.pop()<<" is Popped\n";  
64.  cout<<a.pop()<<" is Popped\n";  
65.  cout<<a.pop()<<" is Popped\n";  
66.  return 0;  
67. }  

Queue
1. #include <iostream>  
2.   
3. using namespace std;  
4.   
5. #define MAX 5           // MAXIMUM CONTENTS IN QUEUE  
6.   
7.   
8. class queue  
9. {  
10.  private:  
11.     int t[MAX];  
12.     int al;      // Addition End  
13.     int dl;      // Deletion End  
14.   
15.  public:  
16.   queue()  
17.   {  
18.     dl=-1;  
19.     al=-1;  
20.   }  
21.   
22.   void del()  
23.   {  
24.      int tmp;  
25.      if(dl==-1)  
26.      {  
27.         cout<<"Queue is Empty";  
28.      }  
29.      else  
30.      {  
31.         for(int j=0;j<=al;j++)  
32.         {  
33.             if((j+1)<=al)  
34.             {  
35.                 tmp=t[j+1];  
36.                 t[j]=tmp;  
37.             }  
38.             else  
39.             {  
40.                 al--;  
41.   
42.             if(al==-1)  
43.                 dl=-1;  
44.             else  
45.                 dl=0;  
46.             }  
47.         }  
48.      }  
49.   }  
50.   
51. void add(int item)  
52. {  
53.     if(dl==-1 && al==-1)  
54.     {  
55.         dl++;  
56.         al++;  
57.     }  
58.    else  
59.    {  
60.         al++;  
61.         if(al==MAX)  
62.     {  
63.             cout<<"Queue is Full\n";  
64.             al--;  
65.             return;  
66.         }  
67.     }  
68.     t[al]=item;  
69.   
70. }  
71.   
72.   void display()  
73.   {  
74.     if(dl!=-1)  
75.    {  
76.     for(int iter=0 ; iter<=al ; iter++)  
77.         cout<<t[iter]<<" ";  
78.    }  
79.    else  
80.     cout<<"EMPTY";  
81.   }  
82.   
83. };  
84.   
85. int main()  
86. {  
87.  queue a;  
88.  int data[5]={32,23,45,99,24};  
89.   
90.  cout<<"Queue before adding Elements: ";  
91.  a.display();  
92.  cout<<endl<<endl;  
93.   
94.  for(int iter = 0 ; iter < 5 ; iter++)  
95.  {  
96.    a.add(data[iter]);  
97.    cout<<"Addition Number : "<<(iter+1)<<" : ";  
98.    a.display();  
99.    cout<<endl;  
100.  }  
101.  cout<<endl;  
102.  cout<<"Queue after adding Elements: ";  
103.  a.display();  
104.  cout<<endl<<endl;  
105.   
106.  for(iter=0 ; iter < 5 ; iter++)  
107.  {  
108.    a.del();  
109.    cout<<"Deletion Number : "<<(iter+1)<<" : ";  
110.    a.display();  
111.    cout<<endl;  
112.  }  
113.  return 0;  
114. }  

Vous aimerez peut-être aussi