The document discusses the implementation of a binary search tree (BST) using both recursive and non-recursive traversal methods. It defines a BST node structure with left and right child pointers. Functions are included to insert nodes, perform inorder, preorder and postorder traversals recursively and non-recursively using stacks. Main inserts sample nodes into the tree and calls the various traversal functions to output the node values in the specified orders.
2 BytesC++ course_2014_c3_ function basics¶meters and overloadingkinan keshkeh
The document discusses functions in C++. It explains that functions can be defined in two ways: with declaration/calling/definition or with just declaration and definition. It provides examples of declaring a function that calculates the average of two numbers, calling that function, and defining the function. It also discusses local and global variables and their scopes. Finally, it lists some common predefined functions in C++ like sqrt, pow, abs, and rand.
The document discusses different types of linked lists including singly linked lists, doubly linked lists, and circular linked lists. It also covers operations for linked lists such as inserting nodes, deleting nodes, and finding the middle node. Examples are provided for implementing linked list operations using C code.
This document contains code for a C++ program that manages traveler details. It includes functions for an administrator menu with options to display traveler lists, search, edit, and delete traveler details. There are also functions for a guest menu to input and display traveler details. Structures are used to store traveler information including name, destination, address, phone number, etc.
This document contains C++ code examples using numerical methods like Newton-Raphson, successive approximation, and secant methods to find the real roots of various equations. It includes 6 questions/problems with sample code to find roots of equations like x^4 - 11x = 8, e^x - 3x^2 = 0, x^3 - 2x - 3 = 0, and sin(x) + 3cos(x) = 2. For each problem, the code provided the numerical method used, input/output examples, and calculations to iteratively approximate the root to within a set tolerance.
The document contains code for several C++ programs that use functions to calculate factorials, sums of even and odd numbers, solutions to quadratic equations, averages, and combinations. Functions are implemented using for, while, do-while loops. Output examples are provided for sample inputs and calculations for each program.
This document discusses binary search trees and provides source code to implement binary search tree traversal operations. It explains that a binary search tree is a binary tree where the left child of a node is less than the parent and the right child is greater. It provides code for preorder, inorder, and postorder traversals of the binary search tree and outputs the traversal order for a sample tree.
The document describes the Aho-Corasick string matching algorithm and provides an example C++ implementation. It constructs a search trie from input strings in the first phase. The second phase creates reverse links from child nodes to their closest parent nodes containing a given character. This allows it to efficiently find all occurrences of strings in a text by traversing the trie. Source code is provided for constructing the trie, creating reverse links, and searching for strings using either a return vector or callback approach.
O quanto você está satisfeito com o código que produz? Mais ainda: o quanto você está satisfeito como profissional? Na busca pela melhoria de nossas aplicações, caímos num grande desafio: melhorar a nós mesmos!
Numa conversa franca e descontraída, Samuel e Victor tentarão apresentar idéias sobre como você pode melhorar seu próprio trabalho e sentir orgulho do que faz.
2 BytesC++ course_2014_c3_ function basics¶meters and overloadingkinan keshkeh
The document discusses functions in C++. It explains that functions can be defined in two ways: with declaration/calling/definition or with just declaration and definition. It provides examples of declaring a function that calculates the average of two numbers, calling that function, and defining the function. It also discusses local and global variables and their scopes. Finally, it lists some common predefined functions in C++ like sqrt, pow, abs, and rand.
The document discusses different types of linked lists including singly linked lists, doubly linked lists, and circular linked lists. It also covers operations for linked lists such as inserting nodes, deleting nodes, and finding the middle node. Examples are provided for implementing linked list operations using C code.
This document contains code for a C++ program that manages traveler details. It includes functions for an administrator menu with options to display traveler lists, search, edit, and delete traveler details. There are also functions for a guest menu to input and display traveler details. Structures are used to store traveler information including name, destination, address, phone number, etc.
This document contains C++ code examples using numerical methods like Newton-Raphson, successive approximation, and secant methods to find the real roots of various equations. It includes 6 questions/problems with sample code to find roots of equations like x^4 - 11x = 8, e^x - 3x^2 = 0, x^3 - 2x - 3 = 0, and sin(x) + 3cos(x) = 2. For each problem, the code provided the numerical method used, input/output examples, and calculations to iteratively approximate the root to within a set tolerance.
The document contains code for several C++ programs that use functions to calculate factorials, sums of even and odd numbers, solutions to quadratic equations, averages, and combinations. Functions are implemented using for, while, do-while loops. Output examples are provided for sample inputs and calculations for each program.
This document discusses binary search trees and provides source code to implement binary search tree traversal operations. It explains that a binary search tree is a binary tree where the left child of a node is less than the parent and the right child is greater. It provides code for preorder, inorder, and postorder traversals of the binary search tree and outputs the traversal order for a sample tree.
The document describes the Aho-Corasick string matching algorithm and provides an example C++ implementation. It constructs a search trie from input strings in the first phase. The second phase creates reverse links from child nodes to their closest parent nodes containing a given character. This allows it to efficiently find all occurrences of strings in a text by traversing the trie. Source code is provided for constructing the trie, creating reverse links, and searching for strings using either a return vector or callback approach.
O quanto você está satisfeito com o código que produz? Mais ainda: o quanto você está satisfeito como profissional? Na busca pela melhoria de nossas aplicações, caímos num grande desafio: melhorar a nós mesmos!
Numa conversa franca e descontraída, Samuel e Victor tentarão apresentar idéias sobre como você pode melhorar seu próprio trabalho e sentir orgulho do que faz.
Numerical solution of ordinary differential equations by using Runge-Kutta Method of Order Two and Runge-Kutta Method of Order Four
How to write the C++ codes?
This document contains code snippets and explanations for 5 questions on structured programming in C++. Question 1 involves writing a program to determine if a number is odd or even. Question 2 prints a multiplication table as a lower triangular matrix using different loop structures. Question 3 solves quadratic equations. Question 4 finds the mean of N numbers using various loops. Question 5 calculates the sum of even and odd numbers up to N using different loops. The document provides the code and output for each question using different loop structures like for, while, and do-while loops.
The document contains 5 questions related to C++ programs for matrix and array operations:
1) Finding the average of numbers in an array
2) Finding the smallest number in a 1D array
3) Adding two matrices
4) Finding the transpose of a matrix
5) Multiplying two matrices (for 2x2 matrices and matrices up to 10x10)
Each question provides the full C++ code to implement the operation and sample input/output.
The document provides an introduction and overview of key C++ concepts such as comments, input/output streams, declarations, data types, reference parameters, const qualifier, default arguments, and function overloading. It describes how each concept works in C++, provides examples, and in some cases compares the concept to how it works in C. The document is aimed at teaching basic C++ concepts.
The document discusses abstract classes and polymorphism in C++. It provides examples of:
1. Defining an abstract base class Linear Data Structure (LDS) with pure virtual functions like push() and having derived classes Stack and Queue implement these functions.
2. Using polymorphism through pointers and references to the base class to call push() on either Stack or Queue objects.
3. A similar example with an abstract base class Shape and derived classes Rectangle and Circle implementing the area() function polymorphically.
This document discusses how to display records from a Northwind database in a JTable using NetBeans and SQL Server. It includes code to connect to the database, define a Product class with getters and setters, a ProductDAO class to retrieve data, and a GUI class to display the results in a JTable. The code retrieves product data including ID, name, category, supplier, price, quantity and units from the database and displays it in the table.
This Java code defines classes for a money transfer application on a mobile device. It includes classes to handle registration, login, viewing account details, and transferring money between accounts by connecting to a backend server via HTTP requests. User interface elements like text fields, forms, images and lists are created to display registration/login screens, account information, and menus to select different actions.
This document contains code snippets from a structured programming tutorial/lab assignment. It includes 5 questions that involve printing text, performing basic math operations on hardcoded and user-inputted values, and converting floating point numbers to integers using different rounding methods. For each question, the code to solve it is provided along with example outputs.
The document contains code snippets and explanations related to C programming concepts like static variables, external variables, scope of variables, const qualifier, etc. It discusses different cases of declaring variables in multiple files and explains the behavior and errors that may occur. It also contains examples demonstrating the memory segments and scope of global, local, static and extern variables.
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
Wiktor Toporek: TypeScript bez wątpienia jest obecnie pewnym standardem wśród obecnych rozwiązań powstałych w JavaScripcie. Ale czy poza byciem dodatkiem który uzupełnia odrobinę dokumentacje i deklaruje kontrakt jakiego typu parametry przyjmują i zwracają np. funkcje jakiejś biblioteki, można wycisnąć z niego coś więcej? Podczas prezentacji wykorzystamy TypeScript do granic możliwości, używając zaawansowanych technik które sprawiają że interfejs naszego API będzie sam kierował używających go developerów na drogę poprawnego użycia, które jest zgodne z naszymi (twórców) założeniami, poprawiając tym samym ich doświadczenia.
This document contains C++ code and output to evaluate definite integrals using numerical integration methods like the Trapezoidal rule, Simpson's 1/3 rule, and Simpson's 3/8 rule. It includes 7 questions that provide code to integrate functions like exp(x), 1/(1+x^2), and sin(x)+cos(x) over different intervals. The code demonstrates how to implement the different numerical integration techniques to compute approximations of definite integrals and compare the results to exact solutions where available.
Our new blog post featuring some common python programming patterns and their C++ equivalents is now up!
Leave us a comment below and let us know what you'd like to see covered in our future posts!
█ Read More
Technical Insights: Introduction to GraphQL|goo.gl/d7PyXH
Container adapters like stack, queue and priority_queue provide interfaces to common data structures like LIFO stack, FIFO queue and sorted priority queue. They are implemented using underlying containers like deque, list, vector. The document explains various container adapter classes and their member functions, and provides code examples to demonstrate their use for problems like reversing a string, checking balanced parentheses and merging cookies.
This document provides an overview of classes in C++. It begins with definitions and concepts related to classes, such as encapsulation and user-defined types. It then provides examples of declaring and defining a simple Time class with attributes like hours, minutes, seconds and methods to set, get, print and change the time. The document also discusses class members, access specifiers, constructors, pointers and references to class objects, and getter and setter methods. It concludes with brief mentions of utility functions, separating interface from implementation, and organizing classes across header and source files.
The Ring programming language version 1.5.3 book - Part 25 of 184Mahmoud Samir Fayed
This document provides summaries of various file handling functions in Ring programming language including Read(), Write(), Dir(), Rename(), Remove(), fopen(), fclose(), fflush(), freopen(), tempfile(), tempname(), fseek(), ftell(), rewind(), fgetpos(), fsetpos(), clearerr(), feof(), ferror(), perror(), fgetc(), fgets(), fputc(), fputs(), ungetc(), fread(), fwrite(), fexists(), and describes how to use numbers and bytes with files. Examples are given to demonstrate the use of these functions for tasks like reading and writing files, getting directory listings, opening and closing files, seeking within files, and checking for errors.
Razvan Rotari shows an experiment to see how far you can go with binding in C++; Cristian Neamtu follows with an insight on how to achieve this in Rust using Serde.
The Neil Armstrong Hall of Engineering at Purdue University represents challenges, sacrifices, and achievements in space exploration. It honors Purdue astronauts like Neil Armstrong, Gene Cernan, the first and last people on the moon, and Virgil "Gus" Grissom, who died in the Apollo 1 accident. The building also celebrates women pioneers and the 22 Purdue alumni who became astronauts, preserving the legacy of spaceflight and building blocks for the future.
South Park Middle School conducted a technology assessment using the Texas STaR Chart to evaluate their performance in key areas of teaching and learning, educator preparation, leadership and infrastructure. The STaR Chart showed their greatest strengths were in internet connectivity and networking, while the greatest weaknesses were in implementing the Technology Applications TEKS, leadership and vision, and budgeting for technology. Although educator professional development scores were higher, more work is needed to increase technology integration across the curriculum through improved leadership, planning and funding support.
Numerical solution of ordinary differential equations by using Runge-Kutta Method of Order Two and Runge-Kutta Method of Order Four
How to write the C++ codes?
This document contains code snippets and explanations for 5 questions on structured programming in C++. Question 1 involves writing a program to determine if a number is odd or even. Question 2 prints a multiplication table as a lower triangular matrix using different loop structures. Question 3 solves quadratic equations. Question 4 finds the mean of N numbers using various loops. Question 5 calculates the sum of even and odd numbers up to N using different loops. The document provides the code and output for each question using different loop structures like for, while, and do-while loops.
The document contains 5 questions related to C++ programs for matrix and array operations:
1) Finding the average of numbers in an array
2) Finding the smallest number in a 1D array
3) Adding two matrices
4) Finding the transpose of a matrix
5) Multiplying two matrices (for 2x2 matrices and matrices up to 10x10)
Each question provides the full C++ code to implement the operation and sample input/output.
The document provides an introduction and overview of key C++ concepts such as comments, input/output streams, declarations, data types, reference parameters, const qualifier, default arguments, and function overloading. It describes how each concept works in C++, provides examples, and in some cases compares the concept to how it works in C. The document is aimed at teaching basic C++ concepts.
The document discusses abstract classes and polymorphism in C++. It provides examples of:
1. Defining an abstract base class Linear Data Structure (LDS) with pure virtual functions like push() and having derived classes Stack and Queue implement these functions.
2. Using polymorphism through pointers and references to the base class to call push() on either Stack or Queue objects.
3. A similar example with an abstract base class Shape and derived classes Rectangle and Circle implementing the area() function polymorphically.
This document discusses how to display records from a Northwind database in a JTable using NetBeans and SQL Server. It includes code to connect to the database, define a Product class with getters and setters, a ProductDAO class to retrieve data, and a GUI class to display the results in a JTable. The code retrieves product data including ID, name, category, supplier, price, quantity and units from the database and displays it in the table.
This Java code defines classes for a money transfer application on a mobile device. It includes classes to handle registration, login, viewing account details, and transferring money between accounts by connecting to a backend server via HTTP requests. User interface elements like text fields, forms, images and lists are created to display registration/login screens, account information, and menus to select different actions.
This document contains code snippets from a structured programming tutorial/lab assignment. It includes 5 questions that involve printing text, performing basic math operations on hardcoded and user-inputted values, and converting floating point numbers to integers using different rounding methods. For each question, the code to solve it is provided along with example outputs.
The document contains code snippets and explanations related to C programming concepts like static variables, external variables, scope of variables, const qualifier, etc. It discusses different cases of declaring variables in multiple files and explains the behavior and errors that may occur. It also contains examples demonstrating the memory segments and scope of global, local, static and extern variables.
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
Wiktor Toporek: TypeScript bez wątpienia jest obecnie pewnym standardem wśród obecnych rozwiązań powstałych w JavaScripcie. Ale czy poza byciem dodatkiem który uzupełnia odrobinę dokumentacje i deklaruje kontrakt jakiego typu parametry przyjmują i zwracają np. funkcje jakiejś biblioteki, można wycisnąć z niego coś więcej? Podczas prezentacji wykorzystamy TypeScript do granic możliwości, używając zaawansowanych technik które sprawiają że interfejs naszego API będzie sam kierował używających go developerów na drogę poprawnego użycia, które jest zgodne z naszymi (twórców) założeniami, poprawiając tym samym ich doświadczenia.
This document contains C++ code and output to evaluate definite integrals using numerical integration methods like the Trapezoidal rule, Simpson's 1/3 rule, and Simpson's 3/8 rule. It includes 7 questions that provide code to integrate functions like exp(x), 1/(1+x^2), and sin(x)+cos(x) over different intervals. The code demonstrates how to implement the different numerical integration techniques to compute approximations of definite integrals and compare the results to exact solutions where available.
Our new blog post featuring some common python programming patterns and their C++ equivalents is now up!
Leave us a comment below and let us know what you'd like to see covered in our future posts!
█ Read More
Technical Insights: Introduction to GraphQL|goo.gl/d7PyXH
Container adapters like stack, queue and priority_queue provide interfaces to common data structures like LIFO stack, FIFO queue and sorted priority queue. They are implemented using underlying containers like deque, list, vector. The document explains various container adapter classes and their member functions, and provides code examples to demonstrate their use for problems like reversing a string, checking balanced parentheses and merging cookies.
This document provides an overview of classes in C++. It begins with definitions and concepts related to classes, such as encapsulation and user-defined types. It then provides examples of declaring and defining a simple Time class with attributes like hours, minutes, seconds and methods to set, get, print and change the time. The document also discusses class members, access specifiers, constructors, pointers and references to class objects, and getter and setter methods. It concludes with brief mentions of utility functions, separating interface from implementation, and organizing classes across header and source files.
The Ring programming language version 1.5.3 book - Part 25 of 184Mahmoud Samir Fayed
This document provides summaries of various file handling functions in Ring programming language including Read(), Write(), Dir(), Rename(), Remove(), fopen(), fclose(), fflush(), freopen(), tempfile(), tempname(), fseek(), ftell(), rewind(), fgetpos(), fsetpos(), clearerr(), feof(), ferror(), perror(), fgetc(), fgets(), fputc(), fputs(), ungetc(), fread(), fwrite(), fexists(), and describes how to use numbers and bytes with files. Examples are given to demonstrate the use of these functions for tasks like reading and writing files, getting directory listings, opening and closing files, seeking within files, and checking for errors.
Razvan Rotari shows an experiment to see how far you can go with binding in C++; Cristian Neamtu follows with an insight on how to achieve this in Rust using Serde.
The Neil Armstrong Hall of Engineering at Purdue University represents challenges, sacrifices, and achievements in space exploration. It honors Purdue astronauts like Neil Armstrong, Gene Cernan, the first and last people on the moon, and Virgil "Gus" Grissom, who died in the Apollo 1 accident. The building also celebrates women pioneers and the 22 Purdue alumni who became astronauts, preserving the legacy of spaceflight and building blocks for the future.
South Park Middle School conducted a technology assessment using the Texas STaR Chart to evaluate their performance in key areas of teaching and learning, educator preparation, leadership and infrastructure. The STaR Chart showed their greatest strengths were in internet connectivity and networking, while the greatest weaknesses were in implementing the Technology Applications TEKS, leadership and vision, and budgeting for technology. Although educator professional development scores were higher, more work is needed to increase technology integration across the curriculum through improved leadership, planning and funding support.
The document discusses different sorting algorithms:
1) Linear search is used to search for a key in an unsorted list by checking each element sequentially until a match is found or the whole list has been searched.
2) Binary search improves on linear search by only checking the middle element and then narrowing the search space to the upper or lower half.
3) Insertion sort iterates through the list and inserts each element into the sorted portion, building up the sorted list one element at a time.
4) Bubble sort iterates through adjacent elements and swaps them if out of order, repeating until the list is fully sorted.
The document describes the creation of tables for an employee database including tables for jobs, locations, departments, and employees. Primary and foreign keys are added to define relationships between the tables. Descriptions are provided for each table. Sample data is inserted and selected from the tables including employees and their associated data. Queries are written to return additional information by joining the tables.
The document is a poem that discusses the fleeting nature of life and moments. It notes how feelings and experiences can't be held onto or repeated. It encourages the reader to keep living in each present moment by keeping their heart open and their perspective fresh. The poem emphasizes appreciating each day as it comes and finding meaning in life's simple beauty.
The document is an agenda for a meeting at Plains High School to discuss the 2010-2011 Texas STaR Chart. The STaR Chart is a summary of technology use and readiness across the campus and district, though not required by law but by Plains ISD. It measures use and capability levels in teaching and learning, educator preparation, leadership and support, and infrastructure. The agenda reviews the 2009-2010 results and provides a link and login information for completing the 2010-2011 STaR Chart, due April 1st.
South Park Middle School conducted a STaR Chart assessment to evaluate its use of educational technology. The assessment showed strengths in internet connectivity and network infrastructure, but weaknesses in implementing technology curriculum standards, leadership and vision for technology, and technology budgeting. While educator training opportunities were increasing, more progress was still needed. The STaR Chart identified areas for the school to focus on improving technology integration, such as providing more leadership and planning around technology, allocating more funds, and ensuring curriculum standards for technology applications were followed in all classrooms.
The document outlines an educational technology action plan for Plains ISD/Plains HS. It includes an organizational flow chart showing the responsibilities of key personnel like the superintendent, district technology director, and principal. It also discusses plans for professional development for teachers in technology integration and classroom uses. The plan will evaluate teachers' use of data and technology in instructional decisions and student performance.
The document describes the structure of tables in an Oracle database - the EMPLOYEE, DEPARTMENT, JOB, and LOCATION tables. It provides the column names and data types for each table. It also includes examples of SQL queries against these tables to return employee names, departments, jobs, locations and other details.
1) The document describes a conceptual journey through scales of size from 1 meter to billions of light years and back down to fractions of a nanometer.
2) It explores scales from the size of leaves to the size of galaxies and discusses what can be observed at each scale of magnitude from 10^0 to 10^23 and 10^-16.
3) The journey is meant to illustrate the constancy of natural laws across vast scales and make the reader consider humanity's place in the universe.
This document implements a linked list data structure in C using nodes with data and pointer to next node fields. It includes functions to insert nodes at the beginning, end or between other nodes, remove nodes from the beginning, end or by data value, and display the list. The main function provides a menu to call these functions and test the linked list implementation.
This program implements a doubly linked list to print the list forward and backward. It defines a Node struct with data, next and prev pointers. It inserts nodes at the head of the list using InsertAtHead() and prints the list forward using Print() and backward using ReversePrint(). It initially inserts two nodes and prints the list both ways. It then inserts three more nodes at the head and prints the list again forward and backward.
This C program implements a snake game using graphics. It initializes a linked list to represent the snake and randomly generates food on the screen. It uses functions to check for collisions with food/body, move the snake according to key presses, and draw the snake/food each frame. The main game loop runs continuously, checking for input, calling functions to update the snake's position and check for collisions, drawing the updated scene, and exiting if the snake collides with itself or the edge of the screen.
This is a c++ binary search program I worked so far but still cant g.pdfkostikjaylonshaewe47
This is a c++ binary search program I worked so far but still cant get it right.
Can anyone help me? Big thanks!!
the client should not be modified
/*
*File: client.cpp
*Author: Yingwu Zhu
*Warning: do not change this file and use it as is.
*Last Modififcation: 10/21/2016
*/
#include
#include
#include
#include
#include
#include \"bst.h\"
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << \"Format: \" << argv[0] << \" [data file]\" << endl;
return 0;
}
ifstream fin(argv[1]);
int cases;
fin >> cases;
int passed = 0;
for (int i = 1; i <= cases; i++) {
cout << \"Checking test case #\" << i << \" ... \";
BST T;
set S;
int n, x;
fin >> n;
bool ok = true;
vector tmp;
int rem = 0;
for (int j = 0; j < n; j++) {
fin >> x;
T.Insert(x);
S.insert(x);
ok &= (T.Search(x) && T.RecurSearch(x));
if (tmp.empty())
tmp.push_back(x);
if (rand()%10 < 3) {
T.Erase(tmp[0]);
S.erase(tmp[0]);
ok &= (T.Search(tmp[0]) == false);
tmp.pop_back();
rem++;
}
}
if (rem
ok &= (T.MaxElement() == *S.rbegin());
while (!S.empty() && !T.Empty()) {
int x = T.MinElement();
ok &= (x == *S.begin());
T.Erase(x);
S.erase(S.begin());
}
cout << (ok ? \"Passed!\" : \"Failed\") << endl;
passed += ok;
}
cout << passed << \" of \" << cases << \" test cases have passed!\ \";
if (passed == cases)
cout << endl << \"Congratulations! Good to Submit Your Code\ \";
else if ((double)passed/cases >= 0.95)
cout << endl << \"You are almost there, but need to fix some bugs.\ \";
else
cout << endl << \"Your code needs a lot of fixes for submission\ \";
return 0;
}
=====================================================================
=======
//bst.h
#ifndef _BST_H_
#define _BST_H_
#include
using namespace std;
class BST {
private:
class Node {
public:
int data;
Node* left;
Node* right;
};
Node* root; //root node pointer
//you may add your auxiliary functions here!
public:
BST(); //constructor
~BST(); //destructor
bool Empty() const;
void Insert(int val);
int MinElement() const;
int MaxElement() const;
bool Search(int val) const;
bool RecurSearch(int val) const;
void Erase(int val);
};
#endif
=====================================================================
=======
/*
bst.cpp
Subject: Binary Seach Tree
Modification Time:10/26/2016
*/
#include
#include\"bst.h\"
using namespace std;
BST::BST(){
root= NULL;
}
BST::~BST(){
delete root;
delete root->left;
delete root->right;
}
bool BST::Empty() const {
return data;
}
void BST::Insert(int val){
Node* p= new Node;
p->data= val;
Node* cur = root;
if(val < cur->data){
cur = cur -> left;
}
else{
right->next=val;
}
}
int BST::MinElement() const {
Node* cur;
while(cur->left != NULL){
cur = cur->left;
}
return(cur->data);
}
int BST::MaxElement() const{
if(root==NULL){
return 0;
}
if(root->left>root->data){
root->data=root->right;
}
else if(root->right>root->data){
root->data=root->right;
}
return root->data;
}
bool BST:: Search(int val) const{
Node* cur;
cur = root;
while(cur!=NULL){
if(cur->data == val){
return true;
}
else if(cur->data .
This document defines a C++ class for a circular linked list. The class contains methods for creating nodes, adding elements to the beginning of the list, deleting elements, and displaying the list. A node struct is also defined containing an info field and a next pointer.
Implement of c & its coding programming by sarmad balochSarmad Baloch
The C program implements a singly linked list with functions to insert and delete nodes, print the list, find a node by key, sort the list by data, and reverse the list. It demonstrates using the functions to create a list, delete all nodes, find and delete a node, sort the list, and reverse it, printing the list after each operation.
In C++ I need help with this method that Im trying to write fillLi.pdffantoosh1
In C++ I need help with this method that I'm trying to write: fillListFromFile( ) : void -- this
method will add elements to the list from a file called linkedListData1.txt HINT: this is where
you will keep track of the number of elements in the list
I have all of the other methods, but I'm stuck on this one and I've added it as the last method in
the application. The code I have so far is below.
.cpp file:
.h file:
main:
#include
#include
#include
#include "Node.h"
using namespace std;
void displayList(Node*);
void insertFront(Node** head, int value);
void insertBack(Node** ptrToHead, int value);
void insertAfter(Node* previous, int value);
void deleteAtN(Node** ptrToHead, int n);
void deleteNode(Node** ptrToHead, int searchVal);
void clearList(Node**);
bool searchVal(Node** head, int value);
int countFrequencyOf(Node** ptrTohead, int value);
int size(Node** ptrTohead);
void displayFromFrontToN(Node** ptrToHead, int n);
void displayFromNToEnd(Node** ptrToHead, int n);
void insertInOrder(Node** head, Node* ptrToHead);
void displayInRows(Node** ptrToHead);
int main()
{
Node* node1 = new Node();
node1->setValue(10);
Node* node2 = new Node();
node2->setValue(20);
Node* node3 = new Node();
node3->setValue(30);
node1->next = node2;
node2->next = node3;
Node* head = node1;
displayList(head);
insertFront(&head, 5);
displayList(head);
insertBack(&head, 50);
displayList(head);
insertBack(&head, 60);
displayList(head);
insertAfter(node2, 25);
displayList(head);
deleteAtN(&head, 2);
displayList(head);
deleteNode(&head, 50);
displayList(head);
clearList(&head);
displayList(head);
insertFront(&head, 5);
insertFront(&head, 10);
insertFront(&head, 20);
insertBack(&head, 50);
searchVal(&head, 50);
displayList(head);
countFrequencyOf(&head, 25);
displayList(head);
insertBack(&head, 25);
insertFront(&head, 25);
countFrequencyOf(&head, 25);
displayList(head);
size(&head);
cout << "add one item to list" << endl;
insertBack(&head, 25);
size(&head);
displayList(head);
cout << "Display From Front To N" << endl;
displayFromFrontToN(&head, 4);
cout << "Display From N To End" << endl;
displayFromNToEnd(&head, 3);
cout << "Display In Rows" << endl;
displayInRows(&head);
insertFront(&head, 12);
insertFront(&head, 17);
insertFront(&head, 22);
insertBack(&head, 58);
cout << "Display In Rows" << endl;
displayInRows(&head);//call displayInRows()
return 0;
}//end main()
void displayList(Node* ptr) {
if (ptr == nullptr)
cout << "empty list" << endl;
else {
while (ptr != nullptr) {
cout << ptr->getValue() << endl;
ptr = ptr->next;
}
}
cout << "---------------------------" << endl;
}//end displayList()
void insertFront(Node** head, int value) {
Node* newNode = new Node();
newNode->setValue(value);
//cout<< newNode->getValue() << endl;
newNode->next = *head;
*head = newNode;
}
void insertBack(Node** ptrToHead, int value) {
Node* newNode = new Node();
newNode->setValue(value);
newNode->next = nullptr;
if (*ptrToHead == nullptr)
{
*ptrToHead = newNode;
}//end if
else
{
Node* last .
program on string in java Lab file 2 (3-year)Ankit Gupta
This document contains C code snippets demonstrating various string and file handling functions in C including:
1. Functions to get the length of a string, concatenate two strings, and search for a substring within a string.
2. Code implementing a B+ tree data structure with functions for initialization, traversal, insertion, and deletion.
3. A threaded binary tree implementation with functions for insertion, deletion, search, and printing the tree.
4. Additional examples of copying one string to another, reading from and writing to binary files, and counting the number of words in a file.
How do you stop infinite loop Because I believe that it is making a.pdffeelinggift
How do you stop infinite loop? Because I believe that it is making an infinite circular list.
c++ code:
Here is the list class:
#ifndef LIN_J_LIST
#define LIN_J_LIST
typedef unsigned int uint;
#include
#include
using namespace std;
/**
* a simplified generic singly linked list class to illustrate C++ concepts
* @author Jerry Lin
* @version 2/17/17
*/
template< typename Object >
class List
{
private:
/**
* A class to store data and provide a link to the next node in the list
*/
class Node
{
public:
/**
* The constructor
* @param data the data to be stored in this node
*/
explicit Node( const Object & data )
: data{ data }, next{ nullptr } {}
Object data;
Node * next;
};
public:
/**
* The constructor for an empty list
*/
List()
: size{ 0 }, first{ nullptr }, last{ nullptr } {}
/**
* the copy constructor-creates and copy the list
*/
List( List && rhs ) = delete;
List( const List & rhs )
{
count = 0;
size = 0;
if(rhs.size != 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first;
size++;
while(current->next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op.
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode->next;
size++;
}
}
// you document and implement this method
}
/**
* the operator= method-copies the list
*/
List & operator=( List && rhs) = delete;
List & operator=( const List & rhs )
{
count = 0;
size = 0;
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
if(rhs.size!= 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first; //create a temporary to store
size++;
while(current -> next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode -> next;
size++;
}
}
return *this;
// you document and implement this method
}
/**
* accessor
* @return count
*/
int get_count() const
{
return count;
}
/**
* The destructor that gets rid of everything that\'s in the list and
* resets it to empty. If the list is already empty, do nothing.
*/
~List()
{
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
}
/**
* Put a new element onto the beginning of the list
* @param item the data the new element will contain
*/
void push_front( const Object& item )
{
Node * new_node = new Node( item );//basic op.
if(is_empty())
{
last = new_node;
}
else
{
new_node->next = first;
}
first = new_node;
size++;
/* you complete the rest */
}
/**
* Remove the element that\'s at the front of the list. Causes an
* assertion error if the list is empty.
*/
void pop_front()
{
assert( !is_empty() );
Node * temp = first;
if( first == last )
{
first = last = nullptr;
}
else
{
first = first->next;
}
delete temp;
size--;
}
/**
* Accessor to return the da.
Need help getting past an error in C++! I have all my code pasted down.docxJason0x0Scottw
The document provides code for a C++ program that stores notes in a linked list and allows the user to perform operations on the notes. The main issue is that function calls in main are producing errors, as the functions need to be called on a class object rather than directly. The document includes the source code, header file defining the classes and functions, and sample input data.
This document contains code snippets for various operations on linked lists and polynomials in C programming language. It includes 9 questions covering topics like:
1. Counting characters, words, digits in a string
2. Squeezing a string by removing spaces
3. Swapping values using pointers
4. Comparing two strings
5. Concatenating two strings
6. Multiplying two matrices
7. Reversing a string
8. Performing insertion, deletion and traversal on singly linked lists
9. Implementing polynomial addition and multiplication by representing polynomials as linked lists
For each question, the C code to implement the operation is provided along with sample input/output.
The document contains 5 programs that implement various data structures and algorithms using C++ templates. Program 1 implements a stack ADT using arrays. Program 2 implements a queue ADT using arrays. Program 3 implements a stack using a singly linked list. Program 4 implements queues using singly linked lists. Program 5 contains parts a-c which implement conversion between infix, postfix and prefix notation as well as evaluation of postfix expressions. Program 6 implements a deque (double ended queue) using a doubly linked list.
The document contains questions and program code snippets related to data structures and algorithms topics.
1) The first section contains a program to remove negative values from a queue using arrays as the underlying data structure.
2) The second section shows functions to implement enqueue, dequeue and display operations on a circular queue using arrays.
3) The third section contains a program to implement an ascending priority queue as a linked list.
I need to fill-in TODOs in .cpp file and in .h file Could some.pdfforladies
I need to fill-in //TODO\'s in .cpp file and in .h file
Could someone help me at least with few of them to give me an idea how deal with it.
***SinglyLinkedList.cpp
#include
#include
#include \"SinglyLinkedList.h\"
void test_constructor() {
SinglyLinkedList lst = {100, 200, 300, 400, 500};
assert(*lst.at(0) == 100);
assert(*lst.at(1) == 200);
assert(*lst.at(2) == 300);
assert(*lst.at(3) == 400);
assert(*lst.at(4) == 500);
assert(lst.size() == 5);
}
void test_remove() {
SinglyLinkedList lst = {100, 200, 300, 400, 500};
lst.remove(2);
assert(*lst.at(0) == 100);
assert(*lst.at(1) == 200);
assert(*lst.at(2) == 400);
assert(*lst.at(3) == 500);
assert(lst.size() == 4);
}
void test_insert() {
// TODO
}
void test_push_back() {
// TODO
}
void test_push_front() {
// TODO
}
void test_append() {
// TODO
}
void test_sum() {
// TODO
}
int main() {
test_constructor();
test_remove();
test_insert();
test_push_back();
test_push_front();
test_append();
test_sum();
}
***SinglyLinkedList.h
#include
#include
template
class SinglyLinkedList {
// Nested class representing the nodes in the list.
class SinglyLinkedListNode {
public:
// The value stored in this node.
T value;
// The next node in the sequence.
SinglyLinkedListNode *next;
SinglyLinkedListNode(T value) :
value(value), next(nullptr) {}
SinglyLinkedListNode(T value, SinglyLinkedListNode *next) :
value(value), next(next) {}
// Return the size (length) of the linked list.
std::size_t size();
};
SinglyLinkedListNode *head;
SinglyLinkedListNode *tail;
public:
// Constructs a new SinglyLinkedList from an initializer_list of type T[].
// This is mostly for convenience, especially when testing.
SinglyLinkedList(std::initializer_list items) : head(nullptr), tail(nullptr) {
if (items.size() == 0) {
return;
}
// initializer_lists were designed to be used iteratively,
// so thats what we do.
// Can you think of how to write this recursively?
auto it = items.begin();
while (it != items.end()) {
this->push_back(*it++);
}
}
// Return a pointer to the value at the given index.
// If the index is larger than the size of the list,
// return a nullptr.
//
// ASIDE: We will cover exceptions later.
T* at(std::size_t i);
// Pushes a new node onto the back of the list.
void push_back(T value);
// Pushes a new node onto the front of the list.
void push_front(T value);
// Return the size (length) of the linked list.
std::size_t size();
// Remove the specified node from the list.
void remove(std::size_t i);
// Insert the value at the index.
void insert(std::size_t i, T value);
// Append the given list to this one.
void append(SinglyLinkedList list);
};
template
T* SinglyLinkedList::at(std::size_t i) {
// TODO
}
template
void SinglyLinkedList::push_back(T value) {
// TODO
// Make sure that this is a O(1) operation!
}
template
void SinglyLinkedList::push_front(T value) {
// TODO
// Make sure that this is a O(1) operation!
}
template
void SinglyLinkedList::remove(std::size_t i) {
// TODO
// Don\'t forget to not only unlink the node, b.
Black box-software-testing-douglas-hoffman2483Chaitanya Kn
This document provides an introduction to black box software testing. Black box testing involves testing software without knowledge of the underlying code, from the customer's perspective. The document outlines several testing paradigms that can be used for black box testing, including domain testing, function testing, regression testing, specification-driven testing, and more. It also discusses test design, test documentation, test automation, and test management strategies. The overall goal is to help readers improve their ability to plan and design effective black box test cases and make good judgments about testing priorities and tradeoffs.
The document discusses the benefits of exercise for mental health. Regular physical activity can help reduce anxiety and depression and improve mood and cognitive functioning. Exercise causes chemical changes in the brain that may help boost feelings of calmness, happiness and focus.
This document describes a system for detecting data leakage when sensitive data is distributed to third party agents. It proposes strategies for allocating data across agents to improve the ability to identify leaks. These strategies include injecting fake records to act as watermarks without modifying real data. The system models agent guilt and develops algorithms to optimize data distribution and detect leaks. It includes modules for data allocation, fake objects, leakage protection, and identifying guilty agents.
The document discusses techniques for detecting data leakage when sensitive data is shared with third parties (agents). It proposes:
1) A model to calculate the probability that each agent is guilty of leaking a set of data (S) that was discovered outside of authorized channels. The model accounts for the likelihood that data in S could be guessed or obtained from other public sources versus leaked by agents.
2) Strategies for allocating data among agents in a way that improves the ability to identify leakers, such as distributing unique or rare records to single agents.
3) The optional addition of "fake" records to the data in a manner similar to digital watermarks, allowing positive identification of leakers if fake
The document contains a list of 20 data structures and algorithms assignments for a first semester MTech computer science lab course. The assignments include implementing linear search, binary search, insertion sort, selection sort, bubble sort, quick sort, merge sort, linked lists, stacks, queues, binary search trees, breadth first search, depth first search, hashing, and heap sort using C, C++, or Java. Students are asked to code solutions and test them.
The document provides an introduction to software testing, covering key concepts like the testing mindset, different types of testing, and how testing fits into the software development lifecycle. It discusses testing approaches like waterfall, iterative development, and agile methodologies. The document is intended to promote the importance of testing and provide testers with foundational knowledge.
The document discusses various topics related to software testing including:
1. The goals of testing are to prevent bugs through early testing and reduce perceived risk of software not working through testing.
2. There are different phases of testing including unit, integration, and system testing with different objectives at each level.
3. Effective testing requires models of the software, environment, potential bugs, and tests themselves which are refined based on unexpected results.
4. Oracles or specifications of expected test outcomes are needed to conduct rigorous testing and reduce the effort of predicting outcomes for each test. Prior test suites and commercial oracles can provide expected outcomes.
The document discusses various Unix/Linux commands for text processing and file management. It describes the commands head, tail, tr, sort, cut, uniq, diff, tee, find, and grep. Head displays the first few lines of a file, tail displays the last few lines, and tr translates or deletes characters. Sort sorts the lines of a text file, cut removes sections from each line, and uniq removes duplicate lines from a sorted file. Diff finds differences between two files.
This document encourages people to stop complaining and start being thankful for what they have by considering those who have less. It notes that while people may feel unhappy with their salary, friends, or other aspects of life, others have it much worse. The document suggests enjoying life as it is and being grateful to God for what one has, as there are always people worse off. It concludes by saying to pursue the few things in life that truly catch your heart.
God does not give people everything they want, only what is necessary and best for them. Sometimes people do not get what they want because God knows better things are available. Even if not satisfied now, one will eventually realize that what God provides is only for their good.
The document simulates different file allocation strategies including sequential, indexed, and linked allocation and shows sample code to implement each. It also simulates different file organization techniques including single-level and two-level directory structures, providing sample code and outputs for each approach. The code samples provide a way to test and understand how these different file allocation and organization techniques work.
How to Manage Your Lost Opportunities in Odoo 17 CRMCeline George
Odoo 17 CRM allows us to track why we lose sales opportunities with "Lost Reasons." This helps analyze our sales process and identify areas for improvement. Here's how to configure lost reasons in Odoo 17 CRM
This slide is special for master students (MIBS & MIFB) in UUM. Also useful for readers who are interested in the topic of contemporary Islamic banking.
Thinking of getting a dog? Be aware that breeds like Pit Bulls, Rottweilers, and German Shepherds can be loyal and dangerous. Proper training and socialization are crucial to preventing aggressive behaviors. Ensure safety by understanding their needs and always supervising interactions. Stay safe, and enjoy your furry friends!
Physiology and chemistry of skin and pigmentation, hairs, scalp, lips and nail, Cleansing cream, Lotions, Face powders, Face packs, Lipsticks, Bath products, soaps and baby product,
Preparation and standardization of the following : Tonic, Bleaches, Dentifrices and Mouth washes & Tooth Pastes, Cosmetics for Nails.
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
Assessment and Planning in Educational technology.pptxKavitha Krishnan
In an education system, it is understood that assessment is only for the students, but on the other hand, the Assessment of teachers is also an important aspect of the education system that ensures teachers are providing high-quality instruction to students. The assessment process can be used to provide feedback and support for professional development, to inform decisions about teacher retention or promotion, or to evaluate teacher effectiveness for accountability purposes.
1. IMPLEMENTATION OF QUEUE USING LINKED LIST
#include<iostream.h>
#include<process.h>
#include<conio.h>
class equeue
{
struct node
{
int info;
node *next;
}*front,*rear;
public:equeue()
{
front=rear=NULL;
}
void insert(void);
void deleted(void);
void display(void);
};
void equeue::insert()
{
node *temp=new node;
cout<<"n Enter Value To Insert:";
cin>>temp->info;
temp->next=NULL;
if(front==NULL)
{
front=rear=temp;
}
else
{
rear->next=temp;
rear=rear->next;
}
}
void equeue::deleted()
{
if(front==NULL)
{
cout<<"n Queue Is Emptyn";
}
else
2. {
if(front==rear)
{
cout<<"n Deleted Element Is :"<<front->info;
front=rear=NULL;
}
else
{
node *temp=front;
cout<<"n Deleted Element Is :"<<temp->info;
front=front->next;
delete(temp);
}
}
}
void equeue::display()
{
if(front==NULL)
cout<<"Queue Is Emptyn";
else
{
node *t=front;
while(t->next!=NULL)
{
cout<<t->info<<"n";
t=t->next;
}
cout<<t->info;
}
}
void main()
{
equeue c;
int ch;
clrscr();
while(1)
{
cout<<"n 1.Insertn 2.Deleten 3.Displayn 4.Exitn";
cout<<"n Enter Your Choice:";
cin>>ch;
switch(ch)
{
case 1:c.insert();
3. break;
case 2:c.deleted();
break;
case 3:c.display();
break;
case 4:exit(0);
break;
default:cout<<"n Enter The Right Choice";
}
}
}
OUTPUT:
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice: 1
Enter the value to insert: 11
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice: 1
Enter the value to insert:22
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice: 1
Enter the value to insert:33
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice: 3
11 22 33
4. 1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice:2
Deleted Element is: 11
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice:2
Deleted Element is: 22
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice:2
Deleted Element is: 33
1.Insert
2.Delete
3.Display
4.Exit
Enter Your Choice:3
Queue is Empty
8. }
void main()
{
int ch1,ch2,num,nd;
dllist st;
clrscr();
while(1)
{
cout<<"n1.Insertn2.Deleten3.Displayn4.Exitn";
cin>>ch1;
switch(ch1)
{
case 1:
{
cout<<"nInsert :n1.Beginningn2.Endn3.Middlen";
cin>>ch2;
switch(ch2)
{
case 1:
{
cout<<"enter the element:";
cin>>num;
st.insertbegin(num);
break;
}
case 2:
{
cout<<"enter the element:";
cin>>num;
st.insertend(num);
break;
}
case 3:
{
cout<<"enter the node after which to insert:";
cin>>nd;
cout<<"enter the element:";
cin>>num;
st.insertmiddle(num,nd);
break;
}
default: cout<<"enter the correct choice";
}
break;
9. }
case 2:
{
cout<<"nDelete:n1.Beginningn2.Endn3.Middle";
cin>>ch2;
switch(ch2)
{
case 1:
{
cout<<"Deletion fron beginning:";
st.deletebegin();
break;
}
case 2:
{
cout<<"Deletion from the end:";
st.deleteend();
break;
}
case 3:
{
cout<<"enter the node to be deleted:";
cin>>nd;
st.deletemiddle(nd);
break;
}
default: cout<<"enter the correct choice";
}
break;
}
case 3:
{
st.display();
break;
}
case 4:exit(0);
default: cout<<"enter the correct choice";
}
}
}
10. OUTPUT:
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice: 1
Insert:
1.Beginning
2.End
3.Middle
1
Enter the element:11
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice:1
Insert:
1.Beginning
2.End
3.Middle
2
Enter the element:22
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice:1
Insert:
1.Beginning
2.End
3.Middle
3
Enter the node after which to insert:11
Enter the element:33
1.Insert
2.Delete
3.Display
4.Exit
11. Enter your choice:3
11->33->22
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice:2
Delete:
1.Beginning
2.End
3.Middle
3
Enter the node to be deleted: 33
Deleted element :33
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice:2
Delete:
1.Beginning
2.End
3.Middle
1
Deletion from the beginning 11
1.Insert
2.Delete
3.Display
4.Exit
Enter your choice:2
Delete:
1.Beginning
2.End
3.Middle
2
Deletion from the end 22
12. IMPLEMNTATION OF BINARY SEARCH TREE NON RECURSIVE
TRAVERSAL
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<malloc.h>
#include<process.h>
struct bstree
{
int data;
struct bstree*left;
struct bstree*right;
}*root=NULL;
class bst
{
private:
public :
void insert(bstree *,int);
void inorder_non_rec(bstree*);
void preorder_non_rec(bstree*);
void postorder_non_rec(bstree*);
};
class stack
{
int top;
bstree *stackel[20];
public:
stack()
{
top=-1;
}
void push(bstree *);
bstree* pop();
int empty()
{
if(top==-1)
return(1);
else
return(0);
}
};
16. void bst::inorder_non_rec(bstree *root)
{
stack stk;
bstree *temp;
if(root!=NULL)
{
temp=root;
do
{
while(temp!=NULL)
{
stk.push(temp);
temp=temp->left;
}
if(!stk.empty())
{
temp=stk.pop();
cout<<temp->data<<" ";
temp=temp->right;
}
else
break;
}while(1);
}
else
cout<<"Empty tree";
}
void main()
{
int info,opt;
char choice;
clrscr();
bst b;
do
{
cout<<"n 1-Insert n 2-Inorder n 3-Preordern 4-Postord n 5. Exitn";
cout<<"n ENTER YOUR CHOICE:";
cin>>opt;
switch(opt)
{
case 1: cout<<"n enter the number :";
cin>>info;
b.insert(root,info);
break;
17. case 2: cout<<"n Inorder n non recursive display is:";
b.inorder_non_rec(root);
break;
case 3: cout<<"nPreorder n non recursive display is:";
b.preorder_non_rec(root);
break;
case 4: cout<<"n Post order n non recursive display is:";
b.postorder_non_rec(root);
break;
case 5: exit(0);
}
}while(1);
}
OUTPUT
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 1
Enter the element: 2
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 1
Enter the element: 67
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 1
Enter the element: 12
1.Insert
2.Inorder
3.Preorder
18. 4.Postorder
5.Exit
Enter your choice: 1
Enter the element: 45
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 1
Enter the element: 74
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 1
Enter the element: 21
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 2
In order
Non recursive display: 2 12 21 45 67 74
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 3
Pre order
Non recursive display: 2 67 12 45 21 74
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 4
Post order
Non recursive display: 21 45 12 74 67 2
19. IMPLEMENTATION OF BINARY SEARCH TREE RECURSIVE TRAVERSAL
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<malloc.h>
#include<process.h>
struct bstree
{
int data;
struct bstree*left;
struct bstree*right;
}*root=NULL;
class bst
{
private:
public :
void insert(bstree *,int);
void inorder(bstree*);
void postorder(bstree *);
void preorder(bstree *);
};
class stack
{
int top;
bstree *stackel[20];
public:
stack()
{
top=-1;
}
void push(bstree *);
bstree* pop();
int empty()
{
if(top==-1)
return(1);
else
return(0);
}
};
22. void bst :: preorder(struct bstree*head)
{
if( head != NULL)
{
cout<<head->data;
preorder(head->left);
preorder(head->right);
}
}
void bst::inorder(bstree *root)
{
stack stk;
bstree *temp;
temp=root;
if(temp!=NULL)
{
inorder(temp->left);
cout<<temp->data;
inorder(temp->right);
}
}
void main()
{
int info,opt;
char choice;
clrscr();
bst b;
do
{
cout<<"n 1-Insert n 2-Inorder n 3-Preordern 4-Postorder n 5. Exitn";
cout<<"n ENTER YOUR CHOICE:";
cin>>opt;
switch(opt)
{
case 1: cout<<"n enter the number :";
cin>>info;
b.insert(root,info);
break;
case 2:cout<<"n recursive display is:";
b.inorder(root);
break;
23. case 3:cout<<"n recursive display is:";
b.preorder(root);
break;
case 4:cout<<"n recursive display is:";
b.postorder(root);
break;
case 5: exit(0);
}
}while(1);
}
OUTPUT
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 1
Enter the element: 2
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 1
Enter the element: 67
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 1
Enter the element: 12
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 1
24. Enter the element: 45
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 1
Enter the element: 74
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 1
Enter the element: 21
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 2
In order
Recursive display: 2 12 21 45 67 74
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 3
Pre order
Recursive display: 2 67 12 45 21 74
1.Insert
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your choice: 4
Post order
Recursive display: 21 45 12 74 67 2
25. IMPLEMENTATION OF Breadth First Search
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int cost[10][10],i,j,k,n,qu[10],front,rare,v,visit[10],visited[10];
main()
{
int m;
cout <<"enter no of vertices";
cin >> n;
cout <<"enter no of edges";
cin >> m;
cout <<"nEDGES n";
for(k=1;k<=m;k++)
{
cin >>i>>j;
cost[i][j]=1;
}
cout <<"enter initial vertex";
cin >>v;
cout <<"Visitied verticesn";
cout << v;
visited[v]=1;
k=1;
while(k<n)
{
for(j=1;j<=n;j++)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
qu[rare++]=j;
}
v=qu[front++];
cout<<v << " ";
k++;
visit[v]=0; visited[v]=1;
}
}
26. OUTPUT:
Enter the no of vertices: 9
Enter the no of edges:9
EDGES
1 2
2 3
1 5
1 4
4 7
7 8
8 9
2 6
5 7
Enter initial vertex: 1
Visited vertices
1 2 4 5 3 6 7 8 9
27. IMPLEMENTATION OF Depth First Search
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10];
main()
{
int m;
cout <<"enterno of vertices";
cin >> n;
cout <<"ente no of edges";
cin >> m;
cout <<"nEDGES n";
for(k=1;k<=m;k++)
{
cin >>i>>j;
cost[i][j]=1;
}
cout <<"enter initial vertex";
cin >>v;
cout <<" VISITED VERTICES";
cout << v <<" ";
visited[v]=1;
k=1;
while(k<n)
{
for(j=n;j>=1;j--)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
stk[top]=j;
top++;
}
v=stk[--top];
cout<<v << " ";
k++;
visit[v]=0; visited[v]=1;
}
}
28. OUTPUT:
Enter the no of vertices: 9
Enter the no of edges:9
EDGES
1 2
2 3
1 5
1 4
4 7
7 8
8 9
2 6
5 7
Enter initial vertex: 1
Visited vertices
1 2 3 6 4 7 8 9 5
29. IMPLEMENTATION OF HEAP SORT
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void heapify(int a[],int i);
void buildheap(int a[]);
void heapsort(int a[]);
int n;
void main()
{
int a[100];
clrscr();
cout<<"enter n valuen";
cin>>n;
int l=n;
cout<<"enter array of elementsn";
for(int i=0;i<n;i++)
cin>>a[i];
heapsort(a);
cout<<"the sorted list of elements are:"<<endl;
for(i=0;i<l;i++)
cout<<a[i]<<endl;
getch();
}
void heapify(int a[],int i)
{
int l,r,large;
l=2*i+1;
r=2*i+2;
if(l<n&&a[l]>=a[i])
large=1;
else
large=i;
if(r<n&&a[r]>=a[large])
large=r;
if(i!=large)
{
int t;
t=a[i];
a[i]=a[large];
a[large]=t;
heapify(a,large);
}
}
30. void buildheap(int a[])
{
int i;
for(i=(n/2)-1;i>=0;i--)
heapify(a,i);
}
void heapsort(int a[])
{
buildheap(a);
for(int i=n-1;i>=1;i--)
{
int t;
t=a[0];
a[0]=a[i];
a[i]=t;
n--;
heapify(a,0);
}
}
OUTPUT:
enter n value
4
enter array of elements
5
6
3
2
the sorted list of elements are:
2
3
5
6
31. IMPLEMENTATION OF PROGRAM TO CONVERT INFIX TO POSTFIX FORM
#include<iostream.h>
#include<conio.h>
#include<string.h>
#define MAXSIZE 100
class STACK_ARRAY
{
int stack[MAXSIZE];
int Top;
public:
STACK_ARRAY()
{
Top=-1;
}
void push(char);
char pop();
int prec(char);
void Infix_Postfix();
};
void STACK_ARRAY::push(char item)
{
if (Top == MAXSIZE-1)
{
cout<<"nThe Stack Is Full";
getch();
}
else
stack[++Top]=item;
}
char STACK_ARRAY::pop()
{
char item='#';
if (Top == -1)
cout<<"nThe Stack Is Empty. Invalid Infix expression";
else
item=stack[Top--];
return(item);
}
int STACK_ARRAY::prec(char symbol)
{
switch(symbol)
{
case '(':
return(1);
32. case ')':
return(2);
case '+':
case '-':
return(3);
case '*':
case '/':
case '%':
return(4);
case '^':
return(5);
default:
return(0);
}
}
void STACK_ARRAY::Infix_Postfix()
{
int len,priority;
char infix[MAXSIZE],postfix[MAXSIZE],ch;
cout<<"nnEnter the infix expression = ";
cin>>infix;
len=strlen(infix);
infix[len++]=')';
push('(');
for(int i=0,j=0;i<len;i++)
{
switch(prec(infix[i]))
{
case 1:
push(infix[i]);
break;
case 2:
ch=pop();
while(ch != '(')
{
postfix[j++]=ch;
ch=pop();
}
break;
case 3:
ch=pop();
while(prec(ch) >= 3)
{
postfix[j++]=ch;
ch=pop();
34. }while(choice == 'Y' || choice == 'y');
}
OUTPUT:
Enter the infix expression:
A+B
The postfix expression is
AB+
Do you wish to continue(Y/y)= y
Enter the infix expression:
A+(B-C)
The postfix expression is
ABC-+
Do you wish to continue(Y/y)=n