id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
23,900 | advanced data structures and implementation exercises prove that the amortized cost of top-down splay is (log nprove that there exist access sequences that require log rotations per access for bottom-up splaying show that similar result holds for top-down splaying modify the splay tree to support queries for the kth smallest item compareempiricallythe simplified top-down splay with the originally described top-down splay write the deletion procedure for red-black trees prove that the height of red-black tree is at most log nand that this bound cannot be substantially lowered show that every avl tree can be colored as red-black tree are all red-black trees avldraw suffix tree and show the suffix array and lcp array for the following input stringsa abcabcabc mississippi once the suffix array is constructedthe short routine shown in figure can be invoked from figure to create the longest common prefix array in the codewhat does rank[irepresentb suppose that lcp[rank[ih show that lcp[rank[ + > show that the algorithm in figure correctly computes the lcp array prove that the algorithm in figure runs in linear time suppose that in the linear-time suffix array construction algorithminstead of constructing three groupswe construct seven groupsusing for sk show that with recursive call to we have enough information to sort the other four groups and show that this partitioning leads to linear-time algorithm implement the insertion routine for treaps nonrecursively by maintaining stack is it worth the effort we can make treaps self-adjusting by using the number of accesses as priority and performing rotations as needed after each access compare this method with the randomized strategy alternativelygenerate random number each time an item is accessed if this number is smaller than ' current priorityuse it as ' new priority (performing the appropriate rotation show that if the items are sortedthen treap can be constructed in linear timeeven if the priorities are not sorted implement some of the tree structures without using the nullnode sentinel how much coding effort is saved by using the sentinel |
23,901 | /create the lcp array from the suffix array is the input array populated from - with available pos sa is an already-computed suffix array - lcp is the resulting lcp array - *void makelcparrayvector sconst vector savector lcp int sa size)vector rankn )sn - forint ++ ranksai iint forint ++ ifranki int saranki ]whilesi =sj ++hlcpranki hifh --hfigure lcp array construction from suffix array suppose we storefor each nodethe number of nullptr links in its subtreecall this the node' weight adopt the following strategyif the left and right subtrees have weights that are not within factor of of each otherthen completely rebuild the subtree rooted at the node show the followinga we can rebuild node in ( )where is the weight of the node the algorithm has amortized cost of (log nper insertion we can rebuild node in - tree in ( log stimewhere is the weight of the node we can apply the algorithm to - treesat cost of (log nper insertion suppose we call rotatewithleftchild on an arbitrary - tree explain in detail all the reasons that the result is no longer usable - tree implement the insertion and range search for the - tree do not use recursion |
23,902 | advanced data structures and implementation determine the time for partial match query for values of corresponding to and for perfectly balanced - treederive the worst-case running time of range query that is quoted in the text (see the - heap is data structure that allows each item to have two individual keys deletemin can be performed with respect to either of these keys the - heap is complete binary tree with the following order propertyfor any node at even depththe item stored at has the smallest key # in its subtreewhile for any node at odd depththe item stored at has the smallest key # in its subtree draw possible - heap for the items ( , )( , )( , )( , )( , how do we find the item with minimum key # how do we find the item with minimum key # give an algorithm to insert new item into the - heap give an algorithm to perform deletemin with respect to either key give an algorithm to perform buildheap in linear time generalize the preceding exercise to obtain - heapin which each item can have individual keys you should be able to obtain the following boundsinsert in (log )deletemin in ( log )and buildheap in (knshow that the - heap can be used to implement double-ended priority queue abstractlygeneralize the - heap so that only levels that branch on key # have two children (all others have onea do we need pointersb clearlythe basic algorithms still workwhat are the new time boundsuse - tree to implement deletemin what would you expect the average running time to be for random treeuse - heap to implement double-ended queue that also supports deletemin implement the pairing heap with nullnode sentinel show that the amortized cost of each operation is (log nfor the pairing heap algorithm in the text an alternative method for combinesiblings is to place all of the siblings on queueand repeatedly dequeue and merge the first two items on the queueplacing the result at the end of the queue implement this variation show that using stack instead of queue in the previous exercise is bad by giving sequence that leads to (ncost per operation this is the left-to-right single-pass merge without decreasekeywe can remove parent links how competitive is the result with the skew heapassume that each of the following is represented as tree with child and parent pointers explain how to implement decreasekey operation binary heap splay tree |
23,903 | figure the plane partitioned by - tree after the insertion of ( ) ( ) ( ) ( ) ( when viewed graphicallyeach node in - tree partitions the plane into regions for instancefigure shows the first five insertions into the - tree in figure the first insertionof splits the plane into left part and right part the second insertionof splits the left part into top part and bottom partand so on for given set of itemsdoes the order of insertion affect the final partitionb if two different insertion sequences result in the same treeis the same partition producedc give formula for the number of regions that result from the partition after insertions show the final partition for the - tree in figure an alternative to the - tree is the quad tree figure shows how plane is partitioned by quad tree initiallywe have region (which is often squarebut need not beeach region may store one point if second point is inserted into regionthen the region is split into four equal-sized quadrants (northeastsoutheastsouthwestand northwestif this places the points in different quadrants (as when is inserted)we are doneotherwisewe continue splitting recursively (as is done when is inserteda for given set of itemsdoes the order of insertion affect the final partitionb show the final partition if the same elements that were in the - tree in figure are inserted into the quad tree tree data structure can store the quad tree we maintain the bounds of the original region the tree root represents the original region each node is either leaf that stores an inserted itemor has exactly four childrenrepresenting four quadrants to perform searchwe begin at the root and repeatedly branch to an appropriate quadrant until leaf (or nullptris reached figure the plane partitioned by quad tree after the insertion of ( ) ( ) ( ) ( ) ( |
23,904 | advanced data structures and implementation draw the quad tree that corresponds to figure what factors influence how deep the (quadtree will bec describe an algorithm that performs an orthogonal range query in quad tree references top-down splay trees were described in the original splay tree paper [ similar strategybut without the crucial rotationwas described in [ the top-down red-black tree algorithm is from [ ] more accessible description can be found in [ an implementation of top-down red-black trees without sentinel nodes is given in [ ]this provides convincing demonstration of the usefulness of nullnode treaps [ are based on the cartesian tree described in [ related data structure is the priority search tree [ suffix trees were first described as position tree by weiner [ ]who provided linear-time algorithm for construction that was simplified by mccreight [ ]and then by ukkonen [ ]who provided the first online linear-time algorithm farach [ provided an alternate algorithm that is the basis for many of the linear-time suffix array construction algorithms numerous applications of suffix trees can be found in the text by gusfield [ suffix arrays were described by manber and myers [ the algorithm presented in the text is due to karkkainen and sanders [ ]another linear-time algorithm is due to ko and aluru [ the linear-time algorithm for constructing the lcp array from suffix array in exercise was given in [ survey of suffix array construction algorithms can be found in [ [ shows that any problem that is solvable via suffix trees is solvable in equivalent time with suffix arrays because the input sizes for practical applications are so largespace is importantand thus much recent work has centered on suffix array and lcp array construction in particularfor many algorithmsa cache-friendly slightly nonlinear algorithm can be preferable in practice to noncache friendly linear algorithm [ for truly huge input sizesin-memory construction is not always feasible [ is an example of an algorithm that can generate suffix arrays for gb of dna sequences in day on single machine with only gb of ramsee also [ for survey of external memory suffix array construction algorithms the - tree was first presented in [ other range-searching algorithms are described in [ the worst case for range searching in balanced - tree was obtained in [ ]and the average-case results cited in the text are from [ and [ the pairing heap and the alternatives suggested in the exercises were described in [ the study [ suggests that the splay tree is the priority queue of choice when the decreasekey operation is not required another study [ suggests that the pairing heap achieves the same asymptotic bounds as the fibonacci heapwith better performance in practice howevera related study [ using priority queues to implement minimum spanning tree algorithms suggests that the amortized cost of decreasekey is not ( fredman [ has settled the issue of optimality by proving that there are sequences for which the amortized cost of decreasekey operation is suboptimal (in factat least (log log )howeverhe has also shown that when used to implement prim' minimum spanning tree algorithmthe pairing heap is optimal if the graph is slightly dense (that isthe number of edges in the graph is ( ( +efor any epettie [ has shown an upper |
23,905 | bound of ( log log for decreasekey howevercomplete analysis of the pairing heap is still open the solutions to most of the exercises can be found in the primary references exercise represents "lazybalancing strategy that has become somewhat popular [ ][ ][ ]and [ describe specific strategies[ shows how to implement all of these strategies in one framework tree that satisfies the property in exercise is weight-balanced these trees can also be maintained by rotations [ part (dis from [ solution to exercises to can be found in [ quad trees are described in [ abouelhodas kurtzand ohlebush"replacing suffix trees with suffix arrays,journal of discrete algorithms ( ) - andersson"general balanced trees,journal of algorithms ( ) - aragon and seidel"randomized search trees,proceedings of the thirtieth annual symposium on foundations of computer science ( ) - baer and schwab" comparison of tree-balancing algorithms,communications of the acm ( ) - barskyu stegeand thomo" survey of practical algorithms for suffix tree construction in external memory,softwarepractice and experience ( - barskyu stegea thomoand upton"suffix trees for very large genomic sequences,proceedings of the eighteenth acm conference on information and knowledge management ( ) - bentley"multidimensional binary search trees used for associative searching,communications of the acm ( ) - bentley and friedman"data structures for range searching,computing surveys ( ) - chang and iyengar"efficient algorithms to globally balance binary search tree,communications of the acm ( ) - chanzy"range search and nearest neighbor search,master' thesismcgill university day"balancing binary tree,computer journal ( ) - ding and weiss"the - heapan efficient multi-dimensional priority queue,proceedings of the third workshop on algorithms and data structures ( ) - farach"optimal suffix tree construction with large alphabets,proceedings of the thirty-eighth annual ieee symposium on foundations of computer science ( ) - flajolet and puech"partial match retrieval of multidimensional data,journal of the acm ( ) - flamigpractical data structures in ++john wileynew york fredman"information theoretic implications for pairing heaps,proceedings of the thirtieth annual acm symposium on the theory of computing ( ) - fredmanr sedgewickd sleatorand tarjan"the pairing heapa new form of self-adjusting heap,algorithmica ( ) - guibas and sedgewick" dichromatic framework for balanced trees,proceedings of the nineteenth annual symposium on foundations of computer science ( ) - gusfieldalgorithms on stringstrees and sequencescomputer science and computational biologycambridge university presscambridgeu |
23,906 | advanced data structures and implementation jones"an empirical comparison of priority-queue and event-set implementations,communications of the acm ( ) - karkkainen and sanders"simple linear work suffix array construction,proceedings of the thirtieth international colloquium on automatalanguages and programming ( ) - kasaig leeh arimuras arikawaand park"linear-time longest commonprefix computation in suffix arrays and its applications,proceedings of the twelfth annual symposium on combinatorial pattern matching ( ) - ko and aluru"space efficient linear time construction of suffix arrays,proceedings of the fourteenth annual symposium on combinatorial pattern matching ( ) - lee and wong"worst-case analysis for region and partial region searches in multidimensional binary search trees and balanced quad trees,acta informatica ( ) - manber and myers"suffix arraysa new method for on-line string searches,siam journal on computing ( ) - martin and ness"optimizing binary trees grown with sorting algorithm,communications of the acm ( ) - mccreight"priority search trees,siam journal of computing ( ) - mccreight" space-economical suffix tree construction algorithm,journal of the acm ( ) - moret and shapiro"an empirical analysis of algorithms for constructing minimum spanning tree,proceedings of the second workshop on algorithms and data structures ( ) - nievergelt and reingold"binary search trees of bounded balance,siam journal on computing ( ) - overmars and van leeuwen"dynamic multidimensional data structures based on quad and - trees,acta informatica ( ) - pettie"towards final analysis of pairing heaps,proceedings of the forty-sixth annual ieee symposium on foundations of computer science ( ) - puglisiw smythand turpin" taxonomy of suffix array construction algorithms,acm computing surveys ( ) - samet"the quadtree and related hierarchical data structures,computing surveys ( ) - sedgewick and waynealgorithms th ed addison-wesley professionalbostonmass sleator and tarjan"self-adjusting binary search trees,journal of the acm ( ) - stasko and vitter"pairing heapsexperiments and analysis,communications of the acm ( ) - stephenson" method for constructing binary search trees by making insertions at the root,international journal of computer and information science ( ) - ukkonen"on-line construction of suffix trees,algorithmica ( ) - vuillemin" unifying look at data structures,communications of the acm ( ) - weiner"linear pattern matching algorithm,proceedings of the fourteenth annual ieee symposium on switching and automata theory( ) - |
23,907 | separate compilation of class templates if we implement class template entirely in its declarationthen as we have seenthere is very little syntax many class templates arein factimplemented this way because compiler support for separate compilation of templates historically has been weak and platform specific thusin many casesthe entire class with its implementation is placed in single header file popular implementations of the standard library follow this strategy to implement class templates figure shows the declaration for the memorycell class template this part isof coursesimple enoughsince it is just subset of the entire class template that we have already seen for the implementationwe have collection of function templates this means that each function must include the template declaration andwhen using the scope operatorthe name of the class must be instantiated with the template argument thus in figure the name of the class is memorycell although the syntax seems innocuous enoughit can get quite cumbersome for instanceto define operatorin the specification requires no extra baggage in the implementationwe would have the brutal code: template const memorycell memorycell::operatorconst memorycell rhs ifthis !&rhs storedvalue rhs storedvaluereturn *this note that some occurrences of memorycell (those after ::can be omittedwith the compiler interpreting memorycell as memorycell |
23,908 | appendix separate compilation of class templates #ifndef memory_cell_h #define memory_cell_h /* class for simulating memory cell *template class memorycell publicexplicit memorycellconst object initialvalue object)const object readconstvoid writeconst object )privateobject storedvalue}#endif figure memorycell class template interface even with thisthe issue now becomes how to organize the class template declaration and the member function template definitions the main problem is that the implementations in figure are not actually functionsthey are simply templates awaiting expansion but they are not even expanded when the memorycell template is instantiated each member function template is expanded only when it is invoked everything in the header the first option is to put both the declaration and the implementation in the header file this would not work for classessince we could get multiply defined functions if several different source files had include directives that processed this headerbut since everything here is templatenot an actual classthere is no problem with this strategyit might be little easier for reading purposes to simply have the header file issue an include directive (prior to the #endifto automatically read in the implementation file with this strategythe cpp files that store the templates are not compiled directly explicit instantiation on some compilers we can achieve many of the benefits of separate compilation if we use explicit instantiation in this scenariowe set up the and cpp files as would normally |
23,909 | #include "memorycell /*construct the memorycell with initialvalue *template memorycell::memorycellconst object initialvalue storedvalueinitialvalue /*return the stored value *template const object memorycell::readconst return storedvalue/*store *template void memorycell::writeconst object storedvalue xfigure memorycell class template implementation be done for classes thusboth figure and figure would be exactly as currently shown the header file would not have an include directive to read the implementation the main routine would only have an include directive for the header file figure shows typical test program if we compile both cpp fileswe find that the instantiated member functions are not found we fix the problem by creating separate file that contains explicit instantiations of the memorycell for the types we use an example of the explicit instantiations is shown in figure this file is compiled as part of the projectand the template implementation file (figure is not compiled as part of the project we have had success using this technique with several older compilers the downside is that all of the template expansions have to be listed by the programmerand when the class template uses other class templatessometimes those have to be listedtoo the advantage is that if the implementation of the member functions in memorycell changesonly memorycellexpand cpp needs to be recompiled |
23,910 | appendix separate compilation of class templates #include "memorycell #include using namespace stdint mainmemorycell memorycell } setvalue ) setvaluem getvalue )cout < getvalue<endlcout < getvalue<endlreturn figure using the memorycell class template #include "memorycell cpptemplate class memorycelltemplate class memorycellfigure instantiation file memorycellexpand cpp |
23,911 | abouelhodam abramsonb abstract data types (adts) - disjoint sets see disjoint sets hash tables see hash tables lists see lists queues see queues stacks see stacks accessors for classes - for matrices - ackermann function activation records - activity-node graphs - acyclic graphs - address-of operator (&for pointers adelson-velskiig adjacency lists for graph representation - references for adjacency matrices adjacent vertices adversary arguments - aggarwala agrawalm ahoa ahujar airport systemsgraphs for albertsonm algorithm analysis components of - computational models for mathematical background for - running times see running times algorithm design approximate bin packing see approximate bin packing backtracking algorithms see backtracking algorithms divide and conquer strategy see divide and conquer strategy dynamic programming see dynamic programming greedy algorithms see greedy algorithms random number generators - randomized algorithms - primality tests - skip lists - all-pairs shortest-path algorithm allenb allpairs function alonn alpha-beta pruning alurus amortized analysis binomial queues - fibonacci heaps see fibonacci heaps references for skew heaps - splay trees - amortized bound times ancestors in trees anderssona approximate bin packing - best fit for - first fit for - next fit for off-line algorithms for - on-line algorithms for references for approximate pattern matching aragonc arbitmany arcsgraph arikawas arimurah arithmetic problems integer multiplication - matrix multiplication - arithmetic series arrays for binary heaps -style - for complete binary trees for graph representation for hash tables see hash tables inversion in - for lists - maps for - for matrices see matrices for queues - for quicksort in sorting see sorting for stacks strings for - for vectors articulation points - ascii character set assertisvalid function assigning pointers assignlow function |
23,912 | index assignment operators assignnum function at function atkinsonm auf der heidef meyer augmenting paths - average-case analysis binary search trees - quicksorts - avl trees - deletion double rotation - references for - single rotation - avlnode structure azary -trees with disk access - references for - back edges in depth-first searches back function for lists for stacks for vectors - backtracking algorithms - games - alpha-beta pruning - minimax algorithm - principles turnpike reconstruction - bacon numbers baerj baeza-yatesr balance conditions avl trees - double rotation - references for - single rotation - balanced binary search trees - balancing symbolsstacks for - balls and bins problem baloghj banachowskil barskym base logarithms base cases induction recursion - baseball card collector problem bavelz bayerr begin function for iterators - for lists - for sets bellt bellmanr bentleyj best-case analysis best fit bin packing algorithm - bestmove function bekesij bhaskars biconnected graphs - big-oh notation - big-omega notation bin packing - best fit for - first fit for - next fit for off-line algorithms for - on-line algorithms for references for binary heaps - heap order - operations - buildheap - decreasekey deletekey deletemin - increasekey insert - remove - references for structure - binary search trees - - average-case analysis - avl trees - double rotation - references for - single rotation - class template for - operations contains - destructors and copy assignment findmin and findmax - insert - remove - optimal - for priority queue implementation red-black see red-black trees references for binary searches binary trees expression - huffman code - implementations traversing - binaryheap class binarynode structure binary search trees binary trees - top-down splay trees - binarysearch function binarysearchtree class binomial queues - amortized analysis - implementation - lazy merging for - operations - references for - structure of binomial trees binomialnode structure binomialqueue class - bipartite graphs bitnerj bjornssony bloomg blumm blumn boggle game bollobasb bookkeeping costs in recursion |
23,913 | borodina boruvkao bottom-up insertion in red-black trees - bound timesamortized - bounds of function growth boyerr braces (})balancing - brackets (]balancing - operator see operators breadth-first searches brightj brodalg brodera brownd brownm brualdir bucket sort - buildbinomialqueue function buildheap function for binary heaps - for heapsorts for huffman algorithm - for leftist heaps burchn +call-by-rvalue-reference copy-and-swap idiom decltype lvalue - - lvalue reference - move assignment operator - move constructor - - range for loop rvalue - - rvalue reference - - size_t - - std::move - std::swap - unordered_map - unordered_set - -style arrays and strings - call-by-rvalue-reference callsstacks for - capacity function for binomial queues for vectors - carlssons carmichael numbers carterj carter-wegman trick cartesian trees cascading cuts for fibonacci heaps caseinsensitivecompare class catalan numbers chaining for hash tables - changh changl changs change function chanzyp character sets character substitution problem - charactersarrays of chazelleb checkers chenj cheritond cheriyanj chess children in trees - christofidesn circle packing problem circular arrays circular linked lists circular logicrecursion as classes and class templates - accessors for compilation - explicit instantiation - constructors for - defaults for - destructors for - interface/implementation separation in - string and vector - syntax for clear function for containers for lists - for priority queues - for vectors - clearyj clique problem clocks for event simulation - for random numbers clone function for binary search trees for binomial queues for leftist heaps for red-black trees for top-down splay trees closest points problem divide and conquer strategy - references for clustering in hash tables code bloat cohenj coin changing problem collections collisions in hashing - double hashing - linear probing - quadratic probing - coloring graphs combinesiblings function combinetrees function - comerd commandspreprocessor - comparable objects - for binary search trees compareandlink function comparison-based sorting comparisons arrays with iterators pointers in selection problem - strings compilation - - explicit instantiation in - hash tables for for header information |
23,914 | index complete binary trees complete graphs compound interest rule in recursion compression file path - computational geometry in divide and conquer strategy turnpike reconstruction - computational models computeadjacentwords function - congruential generators connected graphs connectivity biconnected graphs electrical undirected graphs - consecutive statements in running time const keyword const_iterators - - - constant growth rate constant member functions - constant reference parameter passing by returning values by constructors copy default parameters explicit for iterators - for matrices - containers - see also listsqueuesstacks contains function for binary search trees for binary searches for hash tables - for top-down splay trees continue reserved word contradictionproofs by - convergent series conversions infix to postfix - type convex hulls convex polygons cooks cook' theorem copies for vectors coppersmithd copy-and-swap idiom copy assignment operators - for binary search trees for matrices copy constructors for iterators for matrices copy function copying matrices shallow and deep - costsgraph edges counterexampleproofs by counters in mergesorts - counting radix sort - countingradixsort method cranec createsuffixarray routines - critical paths cross edges cryptography gcd algorithm in prime numbers for - cubic growth rate cuckoo hashing - - cuckoohashtable class - culbersonj culikk current nodes for lists cutting nodes in leftist heaps - -heaps - dags (directed acyclic graphs) - data members for matrices - daya deap queues decision trees for lower bounds - references for declaring objects pointers decltype decreasekey function for binary heaps for binomial queues for dijkstra' algorithm for fibonacci heaps - - for pairing heaps - deep copies vs shallow for vectors defaults for constructor parameters - problems with - definitionsrecursion in delete function for binary search trees for lists delete operations - trees - avl trees - binary heaps - binary search trees - - binomial queues - -heaps - destructors with - fibonacci heaps - hash tables - heapsorts - leftist heaps - linked lists - lists - multiway merges - pairing heaps - pointers - priority queues - red-black trees - sets - skew heaps - skip lists - |
23,915 | splay trees - treaps - vectors - deletekey function deletemax function deletemin function binary heaps - binomial queues - -heaps - dijkstra' algorithm - fibonacci heaps - heapsorts - huffman algorithm - kruskal' algorithm - leftist heaps - multiway merges - pairing heaps - priority queues - skew heaps - demersa dense graphs deon depth-first searches - biconnected graphs - directed graphs - euler circuits - for strong components - undirected graphs - depth of trees deques with heap order dequeue operations dereferencing pointers descendants in trees design rule in recursion destructors - for binary search trees - for matrices devroyel dfs function diamond dequeues dictionariesrecursion in dietzfelbingerm digraphs all-pairs shortest paths in - depth-first searches - representation of - dijkstrae dijkstra function - dijkstra' algorithm - for all-pairs shortest paths - and prim' algorithm - time bound improvements for - dimensions for - trees diminishing increment sorts see shellsort dingy dinice directed acyclic graphs (dags) - directed edges directed graphs - all-pairs shortest paths in - depth-first searches - representation of - directories in extendible hashing - trees for disjoint sets - dynamic equivalence problem in - equivalence relations in for maze generation - path compression for - references for - smart union algorithms for - structure of - worst case analysis for union-by-rank approach - disjsets class - disk / operations in extendible hashing - and running times - in sorting distancesclosest points problem - divide and conquer strategy - closest points problem - components - integer multiplication - matrix multiplication - maximum subsequence sum - in mergesorts - quicksort see quicksort running time of - selection problem - dord dosag double hashing - double rotation operations - doublewithleftchild function doubly linked lists - - - doylej drand function dreyfuss driscollj duh duem dumeya dumpcontents function duplicate elements in quicksorts dynamic equivalence problem - dynamic objects dynamic programming - all-pairs shortest path - optimal binary search trees - ordering matrix multiplications - references for tables vs recursion - eckelb edelsbrunnerh edges in depth-first searches - graph - tree edmondsj eight queens problem eisenbathb electrical connectivity |
23,916 | index employee class - empty function for containers for maps for priority queues for sets for vectors - empty lists enbodyr end function for iterators - for lists for maps for sets #endif preprocessor enqueue operations - eppingerj eppsteind equivalence in disjoint sets - erase function for iterators for lists - for maps erase operations see delete operations erikssonp euclidean distance euclid' algorithm running time - euler circuits - euler' constant eval function - evens event-node graphs event simulation - explicit constructors explicit instantiation - exponential growth rate exponents and exponentiation formulas for running time for - expression trees - extendible hashing - external sorting - algorithm - model for need for references for replacement selection in - factorialsrecursion for faginr farachm fermat' lesser theorem fib function fibonacci function fibonacci heaps - cutting nodes in leftist heaps - for dijkstra' algorithm lazy merging for binomial queues - operations - for priority queues time bound proof for - fibonacci numbers in polyphase merges proofs for recursion for - - file compression file servers find operations see also searches biconnected graphs - binary heaps - binary search trees - binomial queues - disjoint sets - hash tables - lists - maps shortest-path algorithms - top-down splay trees findart function findchain function findcompmove function - findhumanmove function findkth operations findmax function for binary search trees - - for function objects - template for - for top-down splay trees findmin function - for binary heaps - for binary search trees for binomial queues for leftist heaps for top-down splay trees findminindex function - findnewvertexofindegreezero function - findpos function first fit algorithm - first fit decreasing algorithm - fischerm flajoletp flamigb flip function floydr for loops in running time fordl forests for binomial queues in depth-first spanning for disjoint sets for kruskal' algorithm forward edges fotakisd fredmanm friedmanj friend declarations friezea front function fulkersond full nodes - full trees fullers function objects - function templates - functions and function calls member recursive - stacks for - fusseneggerf |
23,917 | gabowh gajewskah galambosg galilz gallerb games alpha-beta pruning - hash tables for minimax algorithm - garbage collection gareym gcd (greatest common divisorfunction general-purpose sorting algorithms geometric series getchainfromprevmap function getname function giancarlor global optimums godboles goldberga golinm gonnetg grahamr grandchildren in trees grandparents in trees graph class - graphs - bipartite breadth-first searches coloring definitions for - depth-first searches see depth-first searches -colorable minimum spanning tree - multigraphs network flow problems - np-completeness - planar references for - representation of - shortest-path algorithms for acyclic graph - all pairs dijkstra' algorithm - example - negative edge costs single source - unweighted - topological sorts for - traveling salesman greatest common divisor (gcdfunction greedy algorithms - approximate bin packing see approximate bin packing for coin changing problem dijkstra' algorithm huffman codes - kruskal' algorithm - maximum-flow algorithms minimum spanning tree - processor scheduling - griesd growth rate of functions - gudese guibasl guptar gusfieldd files hagerupt hakend halting problems hamiltonian cycle - hany handlereorient function hararyf harmonic numbers harriesr hash class template - hash function - hash_map function hash_set function hash tables carter-wegman trick cuckoo hashing - - double hashing in - extendible hashing - hash function - hopscotch hashing - linear probing in - overview - perfect hashing - quadratic probing in - references for - rehashing for - separate chaining for - in standard library - universal hashing - hashama hashentry class - hashtable class - header files - header informationcompilation of header nodes for lists heap orderdeques with heap-order property - heaps - binary see binary heaps leftist see leftist heaps pairing - priority see priority queues skew - heapsort analysis - comparing implementation - references for heapsort function - heavy nodes in skew heaps height of trees avl binary tree traversals complete binary hibbardt hibbard' increments - hiding information hirschbergd hoarec hoeyd homometric point sets hopcroftj hopscotch hashing - horvathe hut |
23,918 | index huangb huffmand huffman codes - hullsconvex hutchinsonj hypotheses in induction - if/else statements in running time implementation/interface separation - implicit type conversions with constructors impossible problems incerpij #include preprocessor increasekey function increment sequences in shellsorts - indegrees of vertices - inductive proofs process - recursion in - infinite loop-checking programs infix to postfix conversion - information hiding information-theoretic lower bounds inheritance for lists init function - initialization list for constructors inorder traversal input size in running time - insert function and insert operations - trees - avl trees - double rotation - single rotation - -trees - binary heaps - binary search trees - - binary searches binomial queues - - -heaps - extendible hashing fibonacci heaps hash tables - huffman algorithm iterators leftist heaps - linked lists - lists - maps multiway merges pairing heaps priority queues - red-black trees - - sets - skew heaps skip lists - splay trees - treaps - insertion sorts - algorithm - analysis - implementation - insertionsort function - instantiationexplicit - intcell class constructors for - defaults for - interface/implementation separation in - pointers in - integers greatest common divisors of - multiplying - interface/implementation separation - internal path lengths inversion in arrays - isactive function isempty function for binary heaps for binary search trees for binomial queues for leftist heaps for top-down splay trees islessthan function isomorphic trees isprime function iterated logarithm iterators const_iterator - for container operations erase getting for lists - for maps - methods for - for sets - stale iyengars jansons jiangt johnsond johnsond johnsons jonassena jonesd josephus problem -colorable graphs - trees - kaasr kaehlere kahna kaned karatsubaa kargerd karlina karltonp karpr karkkainenj karzanova kasait kayaln kernighanb kevin bacon game keys in hashing - for maps - khoongc kingv |
23,919 | kirscha kishimotoa kitten puzzle kleinp knapsack problem knight' tour knuthd kop komlosj korshj kruskalj jr kruskal function - kruskal' algorithm - kuhnh kurtzs labels for class members ladnerr lajoiej laker lamarcaa landaug landise langstonm lapoutrej larmorel last infirst out (lifolists see stacks lawlere lazy binomial queues - lazy deletion avl trees binary search trees hash tables leftist heaps lists - lazy merging binomial queues - fibonacci heaps leaves in trees leec leed leeg leek leftchild function - - leftist heaps - cutting nodes in - merging with - path lengths in - references for skew heaps - leftistheap class - leftistnode structure lehmerd lelewerd lemkep lempela length in binary search trees graph paths tree paths lenstrah jr leongh level-order traversal lewist 'hopital' rule lim liangf lifo (last infirst outlists see stacks light nodes in skew heaps limits of function growth lins linear congruential generators - linear-expected-time selection algorithm - linear growth rate - linear probing - linear worst-case time in selection problem linked lists - circular priority queues skip lists - stacks lippmans list class - listall function lists adjacency arrays for - implementation of - linked see linked lists queues see queues skip - stacks see stacks in stl - vectors for see vectors load factor of hash tables local optimums log-squared growth rate logarithmic growth rate logarithmic running time for binary searches - for euclid' algorithm - for exponentiation - logarithmsformulas for - longest common prefix (lcp) - longest common subsequence problem longest increasing subsequence problem look-ahead factors in games loops graph in running time lower bounds - of function growth maximum and minimum - selection - for sorting - lup luekerg lvalue - - lvalue reference - -ary search trees mahajans main memorysorting in majority problem makeempty function for binary heaps for binary search trees - for binomial queues for hash tables for leftist heaps for lists for top-down splay trees |
23,920 | index makelcparray manacherg manberu map class maps example - for hash tables - implementation - operations - margalito marsagliag martinw mathematics review - for algorithm analysis - exponents logarithms modular arithmetic - proofs - recursion - series - matrices adjacency - data membersconstructorsand accessors for destructorscopy assignmentand copy constructors for multiplying - - operator[for - matrix class - matsumotom maurerw max-heaps - maximum and minimum - maximum-flow algorithms - maximum subsequence sum problem analyzing - running time of - maxit game - maze generation - mccreighte mcdiarmidc mcelroym mckenzieb median-of-median-of-five partitioning - median-of-three partitioning median function - medians samples of in selection problem melhornk melstedp member functions constant signatures for memory address-of operator for in computational models sorting in for vectors memory leaks memorycell class compilation of - template for - merge function and merge operations binomial queues - - -heaps fibonacci heaps leftist heaps - mergesorts pairing heaps - skew heaps - mergesort function analysis of - external sorting - implementation of - multiway - polyphase - references for mersenne twister methods meyerss millerg millerk min-cost flow problems min-heaps min-max heaps minimax algorithm - minimum spanning trees - kruskal' algorithm - prim' algorithm - references for mitzenmacherm modular arithmetic - moffata molodowitchm monierl moorej moorer moretb morinp morrisj motwanir move assignment operator - move constructor - - mullerm mulmuleyk multigraphs multiplying integers - matrices - - multiprocessors in scheduling problem - multiway merges - munroj musserd mutator functions myersg myhash function naorm negative-cost cycles - negative edge costs nessd nested loops in running time network flow - maximum-flow algorithm - references for networksqueues for new operator |
23,921 | for pointers - for vectors newline characters - next fit algorithm - nievergeltj nishimurat node class for lists - nodes binary search trees - binomial trees decision trees expression trees leftist heaps - - linked lists - lists - pairing heaps red-black trees skew heaps - splay trees treaps trees - nondeterministic algorithms nondeterminism nonpreemptive scheduling nonprintable characters nonterminating recursive functions np-completeness easy vs hard - np class references for traveling salesman problem, - null paths in leftist heaps - nullptr null-terminator characters numcols function numrows function object type objects declaring dynamic - function - passing - odlyzkoa off-line algorithms approximate bin packing - disjoint sets ofmany ohlebushe on-line algorithms approximate bin packing - definition disjoint sets one-dimensional circle packing problem one-parameter set operations - onecharoff function - operands in expression trees operators in expression trees - operator!function hash tables - lists - operator(function - operatorfunction lists - matrices - operator+function - operatorfunction in comparable type in square - sets operator<function - operatorfunction - binary search trees - binomial queues in employee iterators leftist heaps lists - red-black trees top-down splay trees vectors - operator=function hash tables - lists - operator[function lists maps - matrices - vectors overloading optimal binary search trees - optmatrix function order binary heaps - matrix multiplications - orlinj 'rourkej orthogonal range queries othello game ottmant overflow in -trees in hash function stack - overloading operators - - overmarsm paghr pair class for maps for sets pairing heaps - panv papadakist papadimitriouc papernova paragraphsright-justifying - parameters default - passing - template parentheses [)balancing - for postfix conversions - parents in trees - parkk parks parse trees partial find partial match queries partialsum function - |
23,922 | index partitions in - trees in quicksorts - in selection problem - passing parameters - patashniko paths augmenting - binary search trees compression - in directory structures - graph halving leftist heaps - shortest see shortest path algorithms in trees patrascum pattern matching problem - percdown function percolatedown function - percolation strategies for binary heaps - for heapsorts perfect hashing - perlisa petersonw petties phases in shellsorts - pippengern pivots in quicksorts - place function - planar graphs plane partitions in - trees plaugerp plaxtonc plies pobletep pohli pointers - in binary search trees - for lists operations for - pointsclosest - polygonsconvex polyphase merges - poonenb pop function for priority queues for stacks - pop_back function for lists for stacks for vectors - pop_front function for lists for vectors portg position of list elements positive-cost cycles postfix expressions - infix conversion to - stacks for - postorder traversal - - potential functions - costs of for splay trees pow (powerfunctions - prattv prefix codes preorder traversal preparataf preprocessor commands - primr prim' algorithm - primary clustering in hash tables prime numbers probability of - proofs for sieve of eratosthenes for tests for - prime table size for hash tables print function in square - for iterators - printable characters printcollection function printhighchangeables function printing queues for recursion for - printlist function printout function printpath function printrange function printtree function for binary search trees for binary trees - for red-black trees - for top-down splay trees priority_queue class - priority queues - binary heaps for see binary heaps -heaps - for dijkstra' algorithm for heapsorts - in huffman algorithm implementations of leftist heaps - model for - references for for selection problem - for simulation - skew heaps - in standard library - priority search trees private labels probability distribution functions probing in hash tables linear - quadratic - processor scheduling problem - progress in recursion proofs - - proper ancestors in trees proper descendants in trees pruning alpha-beta - in backtracking algorithms pseudorandom numbers public labels puechc pughw puglisis push functions for priority queues for stacks - push_back function for lists for stacks for vectors - |
23,923 | unit introduction to data structure and arrays unit introduction to data structure and arrays notes contents objectives introduction abstract data type (adt definition of data structure data structure operations implementation of data structure list adt' adt of singly linked lists implementation arrays implementation array index or subscript dimensions of an array summary keywords self assessment review questions further readings objectives after studying this unityou will be able toz realise basic concept of data describe abstract data type (adtz define data structure know data structure types introduction as static representation of linear ordered list through array leads to wastage of memory and in some cases overflows now we don' want to assign memory to any linear list in advance instead we want to allocate memory to elements as they are inserted in list this requires dynamic allocation of memory semantically data can exist in either of the two forms atomic or structured in most of the programming problems data to be readprocessed and written are often related to each other data items are related in variety of different ways whereas the basic data types such as lovely professional university |
23,924 | notes integerscharacters etc can be directly created and manipulated in programming languagethe responsibility of creating the structured type data items remains with the programmers themselves accordinglyprogramming languages provide mechanism to create and manipulate structured data items abstract data type (adtbefore we move to abstract data type let us understand what data type is most of the languages support basic data types viz integerrealcharacter etc at machine levelthe data is stored as strings containing ' and ' every data type interprets the string of bits in different ways and gives different results in shortdata type is method of interpreting bit patterns every data type has fixed type and range of values it can operate on for examplean integer variable can hold values between the min and max values allowed and carry out operations like additionsubtraction etc for character data typethe valid values are defined in the character set and the operations performed are like comparisonconversion from one case to another etc there are fixed operationswhich can be carried out on them we can formally define data types as formal description of the set of values and operations that variable of given type may take that was about the inbuilt data types one can also create user defined data typesdecide the range of values as well as operations to be performed on them the first step towards creating user defined data type or data structure is to define the logical properties tool to specify the logical properties of data type is abstract data type data abstraction can be defined as separation of the logical properties of the organization of programsdata from its implementation this means that it states what the data should be like it does not consider the implementation details adt is the logical picture of data typein additionthe specifications of the operations required to create and manipulate objects of this data type while defining an adtwe are not concerned with time and space efficiency or any other implementation details of the data structure adt is just useful guideline to use and implement the data type an adt has two parts value definition operation definition value definition is again divided into two parts definition clause condition clause as the name suggests the definition clause states the contents of the data type and condition clause defines any condition that applies to the data type definition clause is mandatory while condition clause is optional examplean integer variable can contain only integer values while character variable can contain only valid character value to understand the above clauses let us consider the adt representation of integer data type in the value definition the definition clause will state that it can contain any number between minimum integer value and the maximum integer value allowed by the computer while the condition clause will impose restriction saying none of the values will have decimal point lovely professional university |
23,925 | notes in operation definitionthere are three parts function precondition postcondition the function clause defines the role of the operation if we consider the addition operation in integers the function clause will state that two integers can be added using this function in generalprecondition specifies any restrictions that must be satisfied before the operation can be applied this clause is optional if we consider the division operation on integers then the precondition will state that the divisor should not be zero so any call for divide operationwhich does not satisfy this conditionwill not give the desired output precondition specifies any condition that may apply as pre-requisite for the operation definition there are certain operations that can be carried out if certain conditions are satisfied for examplein case of division operation the divisor should never be equal to zero only if this condition is satisfied the division operation is carried out hencethis becomes precondition in that case (ampersandshould be mentioned in the operation definition postcondition specifies what the operation does one can say that it specifies the state after the operation is performed in the addition operationthe post condition will give the addition of the two integers figure components of adt adt value definition definition clause operation definition condition clause function precondition postcondition as an examplelet us consider the representation of integer data type as an adt we will consider only two operations addition and division value definition definition clausethe values must be in between the minimum and maximum values specified for the particular computer condition clausevalues should not include decimal point operations add (abfunctionadd the two integers and preconditionno precondition postconditionoutput lovely professional university |
23,926 | notes div (abfunctiondivide by preconditionb ! postconditionoutput / there are two ways of implementing data structure viz static and dynamic in static implementationthe memory is allocated at the compile time if there are more elements than the specified memory then the program crashes in dynamic implementationthe memory is allocated as and when required during run time any type of data structure will have certain basic operations to be performed on its data like insertdeletemodifysortsearch etc depending on the requirement these are the entities that decide the representation of data and distinguish data structures from each other let us see why user defined data structures are essential consider problem where we need to create list of elements any new element added to the list must be added at the end of the list and whenever an element is retrievedit should be the last element of the list one can compare this to pile of plates kept on table whenever one needs platethe last one on the pile is taken and if plate is to be added on the pileit will be kept on the top the description wants us to implement stack let us try to solve this problem using arrays we will have to keep track of the index of the last element entered in the list initiallyit will be set to - whenever we insert an element into the list we will increment the index and insert the value into the new index position to remove an elementthe value of current index will be the output and the index will be decremented by one in the above representationwe have satisfied the insertion and deletion conditions using arrays we could handle our data properlybut arrays do allow access to other values in addition to the top most one we can insert an element at the end of the list but there is no way to ensure that insertion will be done only at the end this is because array as data structure allows access to any of its values at this point we can think of another representationa list of elements where one can add at the endremove from the end and elements other than the top one are not accessible as already discussed this data structure is called as stack the insertion operation is known as push and removal as pop you can try to write an adt for stacks another situation where we would like to create data structure is while working with complex numbers the operations addsubtract division and multiplication will have to be created as per the rules of complex numbers the adt for complex numbers is given below only addition and multiplication operations are considered hereyou can try to write the remaining operations the adt for complex numbers is as followsvalue definition definition clausethis data type has values +ib where and are integers and is equal to under root of - condition clausei term should be present operations addfunctionaddadd two complex numbers ib and ib preconditionno precondition post condition( ( lovely professional university |
23,927 | notes multiplyfunctionmultiply two complex numbers ib and ib preconditionno precondition post conditiona ia ib ia ib abstract data type (adtis mathematical model with collection of operations defined on that model sets of integerstogether with the operations of unionintersection and set differenceform simple example of an adt the adt encapsulates data type in the sense that the definition of the type and all operations on the type can be localized and are not visible to the users of the adt to the usersjust the declaration of the adt and its operations are important abstract data type (adt framework for an object interface what kind of stuff it' be made of (no details) what kind of messages it would receive and kind of action it'll perform when properly triggereddo_this ( conceptualization phase also_this ( object do_that ( from this we figure out object make-up (in terms of data object interface (what sort of messages it would handle? how and when it should act when triggered from outside (public triggerand by another object friendly to itthese concerns lead to an adt definition for the object an abstract data type (adtis set of data items and the methods that work on them an implementation of an adt is translation into statements of programming languageof the declaration that defines variable to be of that adtplus procedure in that language for each operation of the adt an implementation chooses data structure to represent the adteach data structure is built up from the basic data types of the underlying programming language thusif we wish to change the implementation of an adtonly the procedures implementing the operations would change this change would not affect the users of the adt although the terms 'data type''data structureand 'abstract data typesound alikethey have different meanings in programming languagethe data type of variable is the set of values that the variable may assume for examplea variable of type boolean can assume either the value true or the value falsebut no other value an abstract data type is mathematical modeltogether with various operations defined on the model as we have indicatedwe shall design algorithms in terms of adtsbut to implement an algorithm in given programming language lovely professional university |
23,928 | notes we must find some way of representing the adts in terms of the data types and operators supported by the programming language itself to represent the mathematical model underlying an adtwe use data structureswhich are collection of variablespossibly of several data typesconnected in various ways the cell is the basic building block of data structures we can picture cell as box that is capable of holding value drawn from some basic or composite data type data structures are created by giving names to aggregates of cells and (optionallyinterpreting the values of some cells as representing relationships or connections ( pointersamong cells task value definition is one part of adt the second one is definition of data structure data structure is set of data values along with the relationship between the data values sincethe operations that can be performed on the data values depend on what kind of relationships exists among themwe can specify the relationship amongst the data values by specifying the operations permitted on the data values thereforewe can say that data structure is set of values along with the set of operations permitted on them it is also required to specify the semantics of the operations permitted on the data valuesand this is done by using set of axiomswhich describes how these operations workand therefore data structure is made of set of data values set of functions specifying the operations permitted on the data values set of axioms describing how these operations work hencewe conclude that data structure is triple ( , , )where is set of data values is set of functions is set of axioms triple (dfais referred to as an abstract data structure because it does not tell anything about its actual implementation it does not tell anything about how these values will be physically represented in the computer memory and these functions will be actually implemented therefore every abstract data structure is required to be implementedand the implementation of an abstract data structure requires mapping of the abstract data structure to be implemented into the data structure supported by the computer for exampleif the abstract data structure to be implemented is integerthen it can be implemented by mapping into bits which is data structure supported by hardware this requires that every integer data value is to be represented using suitable bit patterns and expressing the operations on integer data values in terms of operations for manipulating bits data structure mainly two types linear type data structure non-linear type data structure linear data structurea linear data structure traverses the data elements sequentiallyin which only one data element can directly be reached exarrayslinked lists lovely professional university |
23,929 | non-linear data structureevery data item is attached to several other data items in way that is specific for reflecting relationships the data items are not arranged in sequential structure extreesgraphs notes basic concept of data the memory (also called storage or coreof computer is simply group of bits (switchesat any instant of the computer' operation any particular bit in memory is either or (off or onthe setting or state of bit is called its value and that is the smallest unit of information set of bit values form data some logical properties can be imposed on the data according to the logical properties data can be segregated into different categories each category having unique set of logical properties is known as data type data type are of two types simple data type or elementary item like integercharacter composite data type or group item like arraystructureunion data structures are of two types primitive data structuresdata can be structured at the most primitive levelwhere they are directly operated upon by machine-level instructions at this leveldata may be character or numericand numeric data may consist of integers or real numbers non-primitive data structuresnon-primitive data structures can be classified as arrayslistsand files an array is an ordered set which contains fixed number of objects no deletions or insertions are performed on arrays the size of the array cannot be changed at bestelements may be changed listby contrastis an ordered set consisting of variable number of elements to which insertions and deletions can be madeand on which other operations can be performed when list displays the relationship of adjacency between elementsit is said to be linearotherwise it is said to be non-linear file is typically large list that is stored in the external memory of computer additionallya file may be used as repository for list items (recordsthat are accessed infrequently from real world perspectivevery often we have to deal with structured data items which are related to each other for instancelet us consider the address of an employee we can take address to be one variable of character type or structured into various fieldsas shown belowaddress addresscharacters ( address house no char ( streetchar( citychar( statechar( pinchar( as shown above address is unstructured address data in this form you cannot access individual items from it you can at best refer to the entire address at one time while in the second fromi address you can access and manipulate individual fields of the address house no streetpin etc given hereunder are two instances of the address and address variables lovely professional university |
23,930 | notes let be two address type variables and be two address type variables the data can now be stored in the following waya sriniwaspurinew delhi house no streetcitysriniwaspuri statedelhi pin one can access different fields of as shown belowa houseno street city "sriniwaspuria state "new delhia pin " data structure is combination of one or more basic data types to form single addressable data type along with operations defined on it note it is data type and hence one can create variables of that type in computer program just as each basic data type allows programmers to perform certain operationsdata structures also let programmers operate on them data abstractiondata abstraction is tool that allows each data structure to be developed in relative isolation from the rest of the solution the study of data structure is organized around collection of abstract data types that includes liststreessetsgraphsand dictionaries data structure operations the data appearing in our data structure is processed by means of certain operations the particular data structure that one chooses for given situation depends largely on the frequency with which specific operations are performed the following four operations play major role transversingaccessing each record exactly once so that certain items in the record may be processed (this accessing or processing is sometimes called 'visitingthe records searchingfinding the location of the record with given key valueor finding the locations of all recordswhich satisfy one or more conditions insertingadding new records to the structure deletingremoving record from the structure sometimes two or more data structure of operations may be used in given situatione we may want to delete the record with given keywhich may mean we first need to search for the location of the record lovely professional university |
23,931 | implementation of data structure notes in this unitwe will discuss the distinguish between the usage and the implementation of data structure this difference is crucial in understanding the concept of the separationdefinition and use that should be practiced for designing good software we then present the implementation of few data structures our main purpose of this course is to describe important data structures and to develop algorithms for the various operations on such data structures while presenting data structure we shall discuss ways to represent it in the computer memory in many caseswe shall assume array to be the primitive structure to house other data structures in this contextwe use the term array to mean one-dimensional array having elements of particular type every high level programming language includes facilities to handle arrays and as such implementation of data structure housed in an array does not offer any problem even in assembly or machine languagesa block of contiguous storage locations can be conveniently considered to be an array for the said purpose borrowing the notation of languagewe shall denote an array type as follows[]thusint [ ]will denote an array of elements where is the name of the array an individual element of this array will be denoted by [iwhere < < in generalan element will be shown as [where in many casesthe relations among the elements of data structure need not be explicitly represented because these are implicitly known when the relations need to be explicitly representedthere are two possible approaches either the relations are represented separately (possible as another data structureor the elements are augmented to include additional fields that represent structural information laterwe shall see many examples of both these approaches and as suchwe do not consider any example at this stage it is clear from the above discussion that sometimes an element will also include structural information in such caseswe shall call it node to make minor distinction between the two thus the distinction between node and an element (or componentis that node is an element (or componentplus the structural information (if anycarried into it task every high level programming language includes facilities to handle arrays what about machine level and assembly level languages list adt' an array is an example of list arrays have fixed sizewhich is declared and fixed at the start of the programand therefore cannot be changed while it is running examplesuppose an array of size has been declared at the start of the program lovely professional university |
23,932 | notes nowthis size cannot be changed while running the program this we all know is static allocation when writing the programwe have to decide on the maximum amount of memory that would be needed if we run the program on small collection of datathen much of the space will go waste if program is run on bigger collection of datathen we may exhaust the space and encounter an overflow consider the following exampleexamplesupposewe define an array of size if we store elements in itit is said to be full and no space is left in it on the contraryif we store elements in itthen positions are empty and virtually uselessresulting in wastage of memory an array with more than half locations empty full array dynamic data structures can avoid these difficulties the idea is to use dynamic memory allocation we allocate memory for individual elements as and when they are required each memory location contains pointer to the location where the successive element is stored pointer or link or reference is variablewhich stores the memory address of some other variable if we use pointers to locate the data in which we are interestedthen we need not worry about where the data is actually storedsince by using pointerwe can let the computer system itself locate the data when required linked lists use the concept of dynamic memory allocation in this respect they are different than arrays every node in linked list contains 'linkto the next node as shown below this link is achieved by using pointers figure linked list structure item structure item next start structure item end this type of list is called linked list because it is list where order is given by links from one item to the next adt of singly linked lists there are various operationswhich can be performed on lists the list abstract data type definition given here contains small collection of basic operationswhich can be performed on lists lovely professional university |
23,933 | list adt specification notes value definitionthe value definition of linked list contains data type for storing the value of the node along with the pointer to the next node the value can be represented using simple data type or collection of basic data types howeverit must necessarily contain at least one pointer to the next structure this can be shown as followsstruct datatype int itemstruct datatype *nextorstruct datatype int itemfloat infochar strstruct datatype *nextdefinition clausethe nodes of the list are all of the same typeand have key field called key the list is logically ordered from smallest unique element of key to the largest value at any position the key of the element is greater than its predecessor and smaller than its successor operations crlistfunctioncreates list and initializes it as empty preconditionsnone postconditionslist is created and is initialized as empty insertfunctioninserts new element into the list either at the beginningin the middle or at the end preconditionsa list already exists postconditionslist is returned with the new element inserted in it deletefunctionsearches list for the element and removes the element from the list preconditionsthe list already exists postconditionsthe list is returned with the element removed from it printfunctiontraverses the list and prints each element preconditionsthe list already exists lovely professional university |
23,934 | notes postconditionslist elements are printed in the order they are present in the list list remains unchanged modifyfunctionsearches for an element and replaces it with new value preconditionsthe list already exists postconditionsthe element if present is modified by new value these are the basic set of operations that might be needed to create and maintain list of elements other operationswhich can be performed on linked listsare counting the elements in list concatenating two lists users can think of more operations like comparing two listsadding the elements of two listsetc depending on specific problem and try building adt' of their own implementation each element of the list is called node and consists of two or more members some members can contain the information pertaining to that node and the others may be pointers to other nodes in case of singly linked listone member consists of such pointer linked list is therefore collection of structures ordered not by their physical placement in memory but by logical links that are stored as part of data in the structure itself the link is in form of pointer to another structure of the same type such structure is represented in ' / ++as followsstruct node int itemstruct node *next}the first member is an integer item and the second pointer to the next node in the list as shown the item can be any complex data type that is it can contain collection of basic data types furtheras we will study doubly linked lists laterwe can have more than two pointers onepointing to the successor node and the other to the predecessor the pointer type is the type of the node itself this node can be shown as followsstruct node int itemfloat infochar strstruct node *next}right nowwe will limit our discussion to singly linked lists with only two membersi one containing the data and the other pointer to the next node lovely professional university |
23,935 | notes figure node node item next such structureswhich contain member field that points to the same structure typeare called self-referential structures node may be represented in general form as followsfigure structure declaration for the node struct label-name type member type member type member struct label-name *next}the node may contain more than one item with different data types howeverone of the items must be pointer of the type label-name the above node with all its members can be depicted as followsmember member membern next node consider simple example to understand the concept of linking suppose we define structure as followsstruct list int valuestruct list *next}assume that the list contains two node viz node and node they are of type struct list and are defined as followsstruct list node ,node lovely professional university |
23,936 | notes this statement creates space for two nodes each containing two empty fields as shown belowfigure creation of the two nodes node node value node next node node value node next the next pointer of node can be made to point to node by the statement node next=&node this statement stores the address of node into the field node next and thus establishes "linkbetween node and node as shown belowfigure node pointing to node node node value node node value address of node node link node value node next now we can assign values to the field value node value= node value= the result is as followsfigure the complete list of two nodes node node link node next assume that the address of node is as you can seethat address is now stored in the next field of node lovely professional university |
23,937 | we may continue this process to create linked list of any number of values each time you need to store value allocate the node and use it in the list for examplenotes node next=&node would add another link also every list must have an end this is necessary for processing the list has special pointer value called null that can be stored in the next field of the last node in the above two-node listthe end of the list is marked as followsnode next=nullthe value of the value member of node can be accessed using the next member of node as followscoutvaluetask write syntax to represent node arrays implementation array group of finite number of identical type of elements accessible by common name an array has name which is also the name of each of its elements for examplelet there be an array abc of integers having elements the same is shown below the names of different elements are shown below abc[ abc[ abc[ abc[ abc[ abc[ index or subscript the integral value that corresponds to the ordinal position of an array element is called index or subscript dimensions of an array on the basis of the number of indices required to access member element in an arrayan array can be classified into the following categories single-dimensional arrays multi-dimensional arrays each type of array has different kind of memory representation memory allocation to arrays member elements of an array are provided contiguous memory locations when program requests the operating system that it intends to create an array the operating system computes the size of one element and multiplies the same with the number of elements requested to obtain the total number of memory cells required the operating system then allocates those many lovely professional university |
23,938 | notes memory locations to the program for array in case the required number of memory cells exceeds the available memory the operating system returns an error code to the program that made the request memory allocation to one-dimensional array one dimensional array is list of finite number of homogeneous data elements ( data elements of the same typesuch that the elements of the array are referenced respectively by an index set consisting of consecutive numbers the elements of the array are stored respectively in successive memory locations the number of elements is called the length or size of the array if not explicitly statedwe will assume the index set consists of the integers in generalthe length or the number of data elements of the array can be obtained from the index set by the formula length ub lb ( whereub is the largest indexcalled the upper bound and lb is the smallest indexcalled the lower boundof the array note note that length ub when lb the elements of an array may be denoted by the subscript notation [ ] [ ] [ ] [nin general linear array with subscript lower bound of "onecan be represented pictorially as in figure given below lb [ if words are allocated for each element or node ( size of data types of elements of array is )then total memory space allocated to array is given bymemory space request (ub lb )* ( if we want to calculate the memory space required for first - elements of an array then slight modification in formula ( will be needed space required ( lb )* lovely professional university |
23,939 | or space required ( lb)* ( notes if the address of [lbis then the address of ith element of array will be given byaddress of [i_+( lb)* ( nowwe can write program for addressing the ith element of single dimensional array we can take _ilb and as input from user and output the address of [iconsider one-dimensional array of figure given below it has five elements each element takes bytes to store suppose address of [ ]= and we want to calculate the address of then from the formula ( we have_ lb address of ( )* address of memory representation of two-dimensional array even though multidimensional arrays are provided as standard data object in most of the high level languagesit is interesting to see how they are represented in memory memory may be regarded as one dimensional with words numbered from to so we are concerned with representing dimensional array in one dimensional memory two dimensional ' narray is collection of data elements such that each element is specified by pair of integers (such as jk)called subscriptswith property that and the element of with first subscript and second subscript will be denoted by aj, or [jktwo dimensional arrays are called matrices in mathematics and tables in business applications consider the following example of array columns [ [ [ [ [ [ [ [ [ two-dimensional array lovely professional university |
23,940 | notes programming language stores the array in either of the two way row major order column major order in row major order elements of st row are stored first in linear order and then comes elements of next row and so on in column major order elements of st column are stored first linearly and then comes elements of next column when above matrix is stored in memory using row major order form then the representation will be as shown in figure ( ( row ( ( ( row ( ( ( row ( representation with column major form will be( ( column ( ( ( column ( ( ( column ( number of elements in any two-dimensional array can be given byno of elements (ub lb (ub lb whereub is upper bound of st dimension lb is lower bound of st dimension ub and lb are upper and lower bounds of nd dimensions lovely professional university ( |
23,941 | lb notes ub lb ith row (ilb (ljub if we want to calculate the number of elements till ist row then no of elements (ub lb ( or no of elements ub lb ( no of elements in ( rows ( (ub lb if be the size of data types of array elements then memory space required for storing - rows will be space required (ub lb ( )* ( if be the address of [lb lb then address of (ilb will beadd (ub lb ( - )* ( address of [ijwill be address of [ijx [(ub lb ( ( )]* ( this is address scheme for row major form for column major form address of [ijx [(ub lb ( ( )]* ( consider two-dimensional matrix of figure suppose address of is and this two dimensional array contains elements of -bytes each we want to calculate the address of then by the formula ( we have ub lb and then add of [( ( ( )]* lovely professional university |
23,942 | notes memory allocation to three-dimensional array suppose we want to calculate address of ( address of th windowi th row and th column lb lb ub ub lb lb ( ub thenfor row major order formaddress of ( +(( *(ub lb )*(ub lb )* ( memory allocation to multi-dimensional array now if we generalize the formulae ( for the dimensions of array then for row major form letadd of (lb lb lb lbnx add of [ [( lb (ub lb (ubn lbn ( lb )(lb lb (ubn lbn )(in lbn )(ubn lbn (in lbn)]* ( now program for address calculation can be made by taking number of dimensionslower and upper bounds of each dimensionsaddress of [lb lb lbnand size as input from user and give address of [ inas output lovely professional university |
23,943 | summary notes data structure is combination of one or more basic data types to form single addressable data type an algorithm is finite set of instructions whichwhen followedaccomplishes particular taskthe termination of which is guaranteed under all casesi the termination is guaranteed for every input the instructions must be unambiguous and the algorithm must produce the output within finite number of executions of its instructions associated with each data structurethere are some algorithms to perform the basic operations on the elements abstract data type (adtis mathematical model with collection of operations defined on that model although the terms 'data type''data structureand 'abstract data typesound alikethey have different meanings keywords linear data structurea linear data structure traverses the data elements sequentiallyin which only one data element can directly be reached non-linear data structureevery data item is attached to several other data items in way that is specific for reflecting relationships the data items are not arranged in sequential structure searchingfinding the location of the record with given key valueor finding the locations of all recordswhich satisfy one or more conditions transversingaccessing each record exactly once so that certain items in the record may be processed self assessment fill in the blanks the memory of computer is simply group of is typically large list that is stored in the external memory of computer an is an ordered set which contains fixed number of objects is combination of one or more basic data types to form single addressable data type along with operations defined on it adding new records to the structure is known as state whether the following statements are true or false an array is an example of list linked lists can not use the concept of dynamic memory allocation each element of the list is called node and consists of two or more members at machine levelthe data is stored as strings containing ' and ' tool to specify the logical properties of data type is abstract data type lovely professional university |
23,944 | notes review questions explain operations of data structure distinguish between linear and non-linear type of data structure write short note on adt "adt is the logical picture of data typeexplain "data abstraction is tool that allows each data structure to be developed in relative isolation from the rest of the solutiondiscuss how will you implement data structureexplain what do you mean by adt of singly listsdiscuss "the list is logically ordered from smallest unique element of key to the largest valueexplain " pointer or link or reference is variablewhich stores the memory address of some other variablediscuss how will you remove record from the structureexplain answersself assessment bits file array data structure inserting true false true true true further readings brian kernighan and dennis ritchiethe programming languageprentice hall data structures and algorithmsshi-kuo changworld scientific data structures and efficient algorithmsburkhard monienthomas ottmannspringer kruse data structure program designprentice hall of indianew delhi mark allen welesdata structure algorithm analysis in second adition addison-wesley publishing rg dromeyhow to solve it by computercambridge university press shi-kuo changdata structures and algorithmsworld scientific sorenson and tremblayan introduction to data structure with algorithms thomas cormencharles eleiserson ronald rivestintroduction to algorithms prentice-hall of india pvt limitednew delhi timothy buddclassic data structures in ++addison wesley lovely professional university |
23,945 | notes www en wikipedia org www web-source net www webopedia com lovely professional university |
23,946 | anil sharmalovely professional university unit linked lists notes contents objectives introduction concept of linked lists representation of linked list inserting node using recursive programs deleting the specified node in singly linked list inserting node after the specified node in singly linked list linked list common errors doubly linked lists circular linked list sorting and reversing linked list merging two sorted lists merging of two circular lists application of linked list summary keywords self assessment review questions further readings objectives after studying this unityou will be able todefine linked lists describe linked lists representation know doubly linked lists explain circular linked lists introduction there are many other operations that are also useful to apply to sequences of elements thus we can form wide variety of similar adts by utilizing different packages of operations any one of these related adts could reasonably go by the name of list howeverwe fix our attention on one particular list adt whose operations give representative sampling of the ideas and problems that arise in working with lists lovely professional university |
23,947 | the standard template library provides rather different data structure called list the stl (standard template librarylist provides only those operations that can be implemented efficiently in list implementation known as doubly linkedwhich we shall study shortly in particularthe stl list does not allow random access to an arbitrary list positionas provided by our list operations for insertionremovalretrievaland replacement another stl template classcalled vectordoes provide some random access to sequence of data values an stl vector bears some similarity to our list adtin particularit provides the operations that can be implemented efficiently in the list implementation that we shall call contiguous in this wayour study of the list adt provides an introduction to the stl classes list and vector notes concept of linked lists an array is represented in memory using sequential mappingwhich has the property that elements are fixed distance apart but this has the following disadvantage it makes insertion or deletion at any arbitrary position in an array costly operationbecause this involves the movement of some of the existing elements when we want to represent several lists by using arrays of varying sizeeither we have to represent each list using separate array of maximum size or we have to represent each of the lists using one single array the first one will lead to wastage of storageand the second will involve lot of data movement so we have to use an alternative representation to overcome these disadvantages one alternative is linked representation in linked representationit is not necessary that the elements be at fixed distance apart insteadwe can place elements anywhere in memorybut to make it part of the same listan element is required to be linked with previous element of the list this can be done by storing the address of the next element in the previous element itself this requires that every element be capable of holding the data as well as the address of the next element thus every element must be structure with minimum of two fieldsone for holding the data valuewhich we call data fieldand the other for holding the address of the next elementwhich we call link field thereforea linked list is list of elements in which the elements of the list can be placed anywhere in memoryand these elements are linked with each other using an explicit link fieldthat isby storing the address of the next element in the link field of the previous element this program uses strategy of inserting node in an existing list to get the list created an insert function is used for this the insert function takes pointer to an existing list as the first parameterand data value with which the new node is to be created as second parametercreates new node by using the data valueappends it to the end of the listand returns pointer to the first node of the list initially the list is emptyso the pointer to the starting node is null thereforewhen insert is called first timethe new node created by the insert becomes the start node subsequentlythe insert traverses the list to get the pointer to the last node of the existing listand puts the address of the newly created node in the link field of the last nodethereby appending the new node to the existing list the main function reads the value of the number of nodes in the list calls iterate that many times by going in while loop to create the links with the specified number of nodes representation of linked list because each node of an element contains two partswe have to represent each node through structure lovely professional university |
23,948 | notes while defining linked list we must have recursive definitionsstruct node int datastruct node linkherelink is pointer of struct node type it can hold the address of variable of struct node type pointers permit the referencing of structures in uniform wayregardless of the organization of the structure being referenced pointers are capable of representing much more complex relationship between elements of structure than linear order initializationmain(struct node * *list*templist temp nulllab exercise programinclude include struct node int datastruct node *link}struct node *insert(struct node *pint nstruct node *temp/if the existing list is empty then insert new node as the starting node *if( ==nullp=(struct node *)malloc(sizeof(struct node))/creates new node data value passes as parameter *if( ==nullprintf("error\ ") lovely professional university |
23,949 | notes exit( ) -data np-link /makes the pointer pointing to itself because it is circular list*else temp /traverses the existing list to get the pointer to the last node of it *while (temp-link !ptemp temp-linktemp-link (struct node *)malloc(sizeof(struct node))/creates new node using data value passes as parameter and puts its address in the link field of last node of the existing list*if(temp -link =nullprintf("error\ ")exit( )temp temp-linktemp-data ntemp-link preturn ( )void printlist struct node * struct node *temptemp pprintf("the data values in the list are\ ")if( !nulldo printf("% \ ",temp->data)lovely professional university |
23,950 | notes temp=temp->linkwhile (temp! )else printf("the list is empty\ ")void main(int nint xstruct node *start null printf("enter the nodes to be created \ ")scanf("% ",& )while - printf"enter the data values to be placed in node\ ")scanf("% ",& )start insert startx )printf("the created list is\ ")printlist start ) inserting node using recursive programs linked list is recursive data structure recursive data structure is data structure that has the same form regardless of the size of the data you can easily write recursive programs for such data structures lab exercise program include include struct node int datastruct node *link}struct node *insert(struct node *pint nstruct node *tempif( ==null lovely professional university |
23,951 | =(struct node *)malloc(sizeof(struct node))notes if( ==nullprintf("error\ ")exit( ) -data np-link nullelse ->link insert( ->link, );/the while loop replaced by recursive call *return ( )void printlist struct node * printf("the data values in the list are\ ")while ( !nullprintf("% \ ", -data) -linkvoid main(int nint xstruct node *start null printf("enter the nodes to be created \ ")scanf("% ",& )while printf"enter the data values to be placed in node\ ")scanf("% ",& )start insert startx )printf("the created list is\ ")printlist start )lovely professional university |
23,952 | notes this recursive version also uses strategy of inserting node in an existing list to create the list an insert function is used to create the list the insert function takes pointer to an existing list as the first parameterand data value with which the new node is to be created as the second parameter it creates the new node by using the data valuethen appends it to the end of the list it then returns pointer to the first node of the list initiallythe list is emptyso the pointer to the starting node is null thereforewhen insert is called the first timethe new node created by the insert function becomes the start node subsequentlythe insert function traverses the list by recursively calling itself the recursion terminates when it creates new node with the supplied data value and appends it to the end of the list deleting the specified node in singly linked list to delete nodefirst we determine the node number to be deleted (this is based on the assumption that the nodes of the list are numbered serially from to nthe list is then traversed to get pointer to the node whose number is givenas well as pointer to node that appears before the node to be deleted then the link field of the node that appears before the node to be deleted is made to point to the node that appears after the node to be deletedand the node to be deleted is freed figures and show the list before and after deletionrespectively lab exercise program include include struct node *delet struct node *int )int length struct node )struct node int datastruct node *link}struct node *insert(struct node *pint nstruct node *tempif( ==nullp=(struct node *)malloc(sizeof(struct node))if( ==nullprintf("error\ ")exit( ) -data np-link null lovely professional university |
23,953 | notes else temp pwhile (temp-link !nulltemp temp-linktemp-link (struct node *)malloc(sizeof(struct node))if(temp -link =nullprintf("error\ ")exit( )temp temp-linktemp-data ntemp-link nullreturn ( )void printlist struct node * printf("the data values in the list are\ ")while ( !nullprintf("% \ ", -data) -linkvoid main(int nint xstruct node *start nullprintf("enter the nodes to be created \ ")scanf("% ",& )while printf"enter the data values to be placed in node\ ")scanf("% ",& )start insert startx )lovely professional university |
23,954 | notes printf(the list before deletion id\ ")printlist start )printf("\ enter the node no \ ")scanf % ",& )start delet (start )printf(the list after deletion is\ ")printlist start )/ function to delete the specified node*struct node *delet struct node *pint node_no struct node *prev*curr int iif ( =null printf("there is no node to be deleted \ ")else if node_no length ( )printf("error\ ")else prev nullcurr pi while node_no prev currcurr curr-linki + if prev =null curr -linkfree curr )else lovely professional university |
23,955 | notes prev -link curr -link free curr )return( )/ function to compute the length of linked list *int length struct node * int count while !null count++ ->linkreturn count figure before deletion pointer node to be deleted figure after deletion pointer inserting node after the specified node in singly linked list to insert new node after the specified nodefirst we get the number of the node in an existing list after which the new node is to be inserted this is based on the assumption that the nodes of the list are numbered serially from to the list is then traversed to get pointer to the nodewhose number is given if this pointer is xthen the link field of the new node is made to point to the node pointed to by xand the link field of the node pointed to by is made to point to the new node figures and show the list before and after the insertion of the noderespectively lovely professional university |
23,956 | notes lab exercise program include include int length struct node )struct node int datastruct node *link}/ function which appends new node to an existing list used for building list *struct node *insert(struct node *pint nstruct node *tempif( ==nullp=(struct node *)malloc(sizeof(struct node))if( ==nullprintf("error\ ")exit( ) -data np-link nullelse temp pwhile (temp-link !nulltemp temp-linktemp-link (struct node *)malloc(sizeof(struct node))if(temp -link =nullprintf("error\ ")exit( )temp temp-link lovely professional university |
23,957 | notes temp-data ntemp-linknullreturn ( )/ function which inserts newly created node after the specified node *struct node newinsert struct node *pint node_noint value struct node *temptemp int iif node_no length ( )printf("errorthe specified node does not exist\ ")exit( )if node_no = temp struct node )malloc sizeof struct node ))if temp =null printfcannot allocate \ ")exit ( )temp -data valuetemp -link pp temp else temp while node_no + temp temp-link temp struct node )malloc sizeof(struct node))if temp =null printf ("cannot allocate \ ")lovely professional university |
23,958 | notes exit( temp -data value temp -link temp -linktemp -link temp return ( )void printlist struct node * printf("the data values in the list are\ ")while ( !nullprintf("% \ ", -data) -linkvoid main (int nint xstruct node *start nullprintf("enter the nodes to be created \ ")scanf("% ",& )while printf"enter the data values to be placed in node\ ")scanf("% ",& )start insert startx )printf(the list before deletion is\ ")printlist start )printf(\ enter the node no after which the insertion is to be done\ ")scanf % ",& )printf("enter the value of the node\ ")scanf("% ",& )start newinsert(start, , )printf("the list after insertion is \ ")printlist(start) lovely professional university |
23,959 | notes figure before insertion pointer node to be inserted figure after insertion pointer task write program to insert node in singly linked list linked list common errors here is summary of common errors of linked lists read these carefullyand read them again when you have problem that you need to solve allocating new node to step through the linked listonly pointer variable is needed confusing the and the -operators not setting the pointer from the last node to (null not considering special cases of inserting/removing at the beginning or the end of the linked list applying the delete operator to node (calling the operator on pointer to the nodebefore it is removed delete should be done after all pointer manipulations are completed pointer manipulations that are out of order these can ruin the structure of the linked list task draw diagram to illustrate the configuration of linked nodes that is created by the following statements node * new node( )node * ->next new node( )node * ->next new node( )lovely professional university |
23,960 | notes doubly linked lists in the single linked list each node provides information about where the next node is in the list it faces difficulty if we are pointing to specific nodethen we can move only in the direction of the links it has no idea about where the previous node lies in memory the only way to find the node which precedes that specific node is to start back at the beginning of the list the same problem arises when one wishes to delete an arbitrary node from single linked list since in order to easily delete an arbitrary node one must know the preceding node this problem can be avoided by using doubly linked listwe can store in each node not only the address of next node but also the address of the previous node in the linked list node in doubly linked list has three fields (figure data left link right link figure node of doubly linked list link data link left link keeps the address of previous node and right link keeps the address of next node doubly linked list has following property = ->llink->rlink= ->rlink->llink link link this formula reflects the essential virtue of this structurenamelythat one can go back and forth with equal ease implementation of doubly linked list structure of node of doubly linked list can be defined asstruct node int datastruct node *llinkstruct node *rlinklab exercise program include include struct dnode lovely professional university |
23,961 | notes int datastruct node *left*right}struct dnode *insert(struct dnode *pstruct dnode **qint nstruct dnode *temp/if the existing list is empty then insert new node as the starting node *if( ==nullp=(struct dnode *)malloc(sizeof(struct dnode))/creates new node data value passed as parameter *if( ==nullprintf("error\ ")exit( ) -data np-left ->right =null* = else temp (struct dnode *)malloc(sizeof(struct dnode))/creates new node using data value passed as parameter and puts its address in the temp *if(temp =nullprintf("error\ ")exit( )temp-data ntemp->left (* )temp->right null(*qtemplovely professional university |
23,962 | notes return ( )void printforstruct dnode * printf("the data values in the list in the forward order are:\ ")while ( !nullprintf("% \ ", -data) -right/ function to count the number of nodes in doubly linked list *int nodecount (struct dnode * int count= while ( !nullcount ++ ->rightreturn(count)/ function which inserts newly created node after the specified node in doubly linked list *struct node newinsert struct dnode *pint node_noint value struct dnode *temptemp int iif node_no nodecount ( )printf("errorthe specified node does not exist\ ")exit( )if node_no = temp struct dnode )malloc sizeof struct dnode ))if temp =null lovely professional university |
23,963 | printfcannot allocate \ ")notes exit ( )temp -data valuetemp -right ptemp->left null temp else temp while node_no + temp temp-right temp struct dnode )malloc sizeof(struct dnode))if temp =null printf("cannot allocate \ ")exit( )temp -data value temp -right temp -righttemp -left temptemp ->right->left temp temp ->left->right temp return ( )void main(int nint xstruct dnode *start null struct dnode *end nullprintf("enter the nodes to be created \ ")scanf("% ",& )while lovely professional university |
23,964 | notes printf"enter the data values to be placed in node\ ")scanf("% ",& )start insert start&end, )printf("the created list is\ ")printfor start )printf("enter the node number after which the new node is to be inserted\ ")scanf("% ",& )printf("enter the data value to be placed in the new node\ ")scanf("% ",& )start=newinsert(start, , )printfor(start)explanation to insert new node in doubly linked chainit is required to obtain pointer to the node in the existing list after which new node is to be inserted to obtain this pointerthe node number after which the new node is to be inserted is given as input the nodes are assumed to be numbered as , , etc starting from the first node the list is then traversed starting from the start node to obtain the pointer to the specified node let this pointer be new node is then created with the required data valueand the right link of this node is made to point to the node to the right of the node pointed to by and the left link of the newly created node is made to point to the node pointed to by the left link of the node which was to the right of the node pointed to by is made to point to the newly created node the right link of the node pointed to by is made to point to the newly created node question write program to delete specific node from the linked list circular linked list circular linked list is another remedy for the drawbacks of the single linked list besides doubly linked list slight change to the structure of linear list is made to convert it to circular linked listlink field in the last node contains pointer back to the first node rather than null (see figure figure circular linked list from any point in such list it is possible to reach any other point in the list if we begin at given node and traverse the entire listwe ultimately end up at the starting point lovely professional university |
23,965 | notes lab exercise programhere is program for building and printing the elements of the circular linked list include include struct node int datastruct node *link}struct node *insert(struct node *pint nstruct node *temp/if the existing list is empty then insert new node as the starting node *if( ==nullp=(struct node *)malloc(sizeof(struct node))/creates new node data value passes as parameter *if( ==nullprintf("error\ ")exit( ) -data np-link /makes the pointer pointing to itself because it is circular list*else temp /traverses the existing list to get the pointer to the last node of it *while (temp-link !ptemp temp-linktemp-link (struct node *)malloc(sizeof(struct node))/creates new node using data value passes as parameter and puts its address in the link field of last node of the existing list*lovely professional university |
23,966 | notes if(temp -link =nullprintf("error\ ")exit( )temp temp-linktemp-data ntemp-link preturn ( )void printlist struct node * struct node *temptemp pprintf("the data values in the list are\ ")if( !nulldo printf(% \ ",temp->data)temp=temp->linkwhile (temp!pelse printf("the list is empty\ ")void main(int nint xstruct node *start null printf("enter the nodes to be created \ ")scanf("% ",& )while printf"enter the data values to be placed in node\ ")scanf("% ",& )start insert startx )printf("the created list is\ ")printlist start ) lovely professional university |
23,967 | this program appends new node to the existing list (that isit inserts new node in the existing list at the end)and it makes the link field of the newly inserted node point to the start or first node of the list this ensures that the link field of the last node always points to the starting node of the list notes sorting and reversing linked list to sort linked listfirst we traverse the list searching for the node with minimum data value then we remove that node and append it to another list which is initially empty we repeat this process with the remaining list until the list becomes emptyand at the endwe return pointer to the beginning of the list to which all the nodes are movedas shown in figure figure sorting of linked list null start list to be sorted null start null after the first pass to reverse listwe maintain pointer each to the previous and the next nodethen we make the link field of the current node point to the previousmake the previous equal to the currentand the current equal to the nextas shown in figure figure linked list showing the previouscurrentand next nodes at some point during reversal process null prev curr next thereforethe code needed to reverse the list isprev nullwhile (curr !nullnext curr->linkcurr -link prevprev currcurr next merging two sorted lists merging of two sorted lists involves traversing the given lists and comparing the data values stored in the nodes in the process of traversing lovely professional university |
23,968 | notes if and are the pointers to the sorted lists to be mergedthen we compare the data value stored in the first node of the list pointed to by with the data value stored in the first node of the list pointed to by andif the data value in the first node of the list pointed to by is less than the data value in the first node of the list pointed to by qmake the first node of the resultant/merged list to be the first node of the list pointed to by pand advance the pointer to make it point to the next node in the same list if the data value in the first node of the list pointed to by is greater than the data value in the first node of the list pointed to by qmake the first node of the resultant/merged list to be the first node of the list pointed to by qand advance the pointer to make it point to the next node in the same list repeat this procedure until either or becomes null when one of the two lists becomes emptyappend the remaining nodes in the non-empty list to the resultant list null null two sorted lists before merging if the above lists given as inputwhat would be the output of the program after each passr temp null null null null null null null after the first pass temp null after the second pass temp null after the third pass contd lovely professional university |
23,969 | notes null temp null null after the fourth pass null temp null null after the fifth pass null temp after the sixth pass null null temp final merged list merging of two circular lists in order to merge or concatenate the two non-empty circular lists pointed to by and qit is required to make the start of the resultant list then the list pointed to by is required to be traversed until its endand the link field of the last node must become the pointer after thatthe list pointed to by is required to be traversed until its endand the link field of the last node is required to be made lovely professional university |
23,970 | notes the given lists the resultant list you can merge two lists into one list the following program merges two circular lists lab exercise programinclude include struct node int datastruct node *link}struct node *insert(struct node *pint nstruct node *temp/if the existing list is empty then insert new node as the starting node *if( ==nullp=(struct node *)malloc(sizeof(struct node))/creates new node data value passes as parameter *if( ==null lovely professional university |
23,971 | notes printf("error\ ")exit( ) -data np-link /makes the pointer pointing to itself because it is circular list*else temp /traverses the existing list to get the pointer to the last node of it *while (temp-link !ptemp temp-linktemp-link (struct node *)malloc(sizeof(struct node))/creates new node using data value passes as parameter and puts its address in the link field of last node of the existing list*if(temp -link =nullprintf("error\ ")exit( )temp temp-linktemp-data ntemp-link preturn ( )void printlist struct node * struct node *temptemp pprintf("the data values in the list are\ ")if( !nulllovely professional university |
23,972 | notes do printf("% \ ",temp->data)temp=temp->linkwhile (temp! )else printf("the list is empty\ ")struct node *merge(struct node *pstruct node *qstruct node *temp=nullstruct node * =nullr ptemp pwhile(temp->link !ptemp temp->linktemp->link qtemp qwhiletemp->link !qtemp temp->linktemp->link rreturn( )void main(int nint xstruct node *start =null struct node *start =nullstruct node *start =null/this will create the first circular list nodes*printf("enter the number of nodes in the first list \ ")scanf("% ",& )while - printf"enter the data value to be placed in node\ ")scanf("% ",& )start insert start )printf("the first list is\ ") lovely professional university |
23,973 | notes printlist start )/this will create the second circular list nodes*printf("enter the number of nodes in the second list \ ")scanf("% ",& )while - printf"enter the data value to be placed in node\ ")scanf("% ",& )start insert start )printf("the second list is:\ ")printlist start )start merge(start ,start )printf("the resultant list is:\ ")printlist(start )task write program to reverse linked list application of linked list polynomials in general are represented by the following equationf(xcixei ci xei + xe where ci are non zero coefficients of variable and ei are exponents such that ei ei ei examplef ( ( + these polynomials can be added to form another polynomial let (xf ( + (xf ( this is achieved by adding coefficients of variables with same exponent value these polynomials can be maintained using linked list to achieve this each term will be represented by node and each node should consist of three elements namely coefficientsexponents and link to the next term (represented by another nodestruct poly coef exp link float coeflovely professional university |
23,974 | notes int expstruct poly linkfor instancethe polynomial ( ) will be stored asf( - null while maintaining the polynomial it is assumed that the exponent of each successive term is less than that of the previous term we can use these linked lists to add two polynomials to add two polynomials together we examine their terms starting at the nodes pointed to by and (two pointers used to move along the terms of two polynomialsif the exponents of two terms are equalthen the coefficients are added and new term created for the result if the exponents of the current term in is less than the exponent of current term of qthen duplicate of the term is created and attached to the pointers and (pointer to result termare advanced similar action is taken if exp( >exp( null null for the nd term exp (pexp (qhence - - - now exp (pexp (qhence now exhorted hence - the function for adding two polynomials is given belowpolyadd (struct polypstruct poly*qstruct poly * zmalloc(sizeof(struct poly))if ( =null & ==nullreturnwhile ( !=null & !=nullif ( -exp ->exp lovely professional university |
23,975 | ->exp= ->expz ->coef= ->coefnotes = -linkif ( ->expexpz->exp= ->expz ->coef= ->coefq= ->linkif( -exp= ->exp)!= ->exp= ->expz->coef= ->expp= ->linkq= ->linkz->link malloc(sizeof(struct poly)) = -linkwhile ( !=nullz->exp= ->expz->coef= ->coefz->linkmalloc(sizeof(struct poly)) = ->linkp= ->linkwhile ( !=nullz->exp= ->expz->coef= ->coefz->link=malloe(sizeof(struct poly)) = ->linkq= ->linkcursor implementation of linked lists consider case where we have two linked lists pointed to by two different pointerssay and respectivelyand we want to concatenate nd list at the end of the first list we can do it by traversing first list till the end and then store the address of first node in the second listin the link field of last node of first list suppose we are traversing first list by pointer tempthen we can concatenate the list by the statement (figure temp -link qlovely professional university |
23,976 | notes figure (alists before concatenation and (blist after concatenation null null (atemp null (bthe function to achieve this is given belowconcatenate (struct node *pstruct node *qstruct node *temptemp pif ( =null)/if first list is null then concatenated /list will be only second list and will be else //pointed by ptemp pwhile (temp -link nulltemp temp -linktemp -link summary the foremost advantage of linked lists in dynamic storage is flexibility advantages overflow is no problem until the computer memory is actually exhausted especially when the individual entries are quite largeit may be difficult to determine the overflow amount of contiguous static storage that might be needed for the required arrays while keeping enough free for other needs with dynamic allocationthere is no need to attempt to make such decisions in advance changesespecially insertions and deletionscan be made in the middle of changes linked list more quickly than in the middle of contiguous list if the structures are largethen it is much quicker to change the values of few pointers than to copy the structures themselves from one location to another disadvantages the first drawback of linked lists is that the links themselves take space that might otherwise be needed for additional data in most systemsa pointer requires the same amount of storage (one wordas does an integer thus list of integers will require double the space in linked storage that it would require in contiguous storage lovely professional university |
23,977 | keywords notes circular linked lista linear linked list in which the last element points to the first elementthusforming circle doubly linked lista linear linked list in which each element is connected to the two nearest elements through pointers linear lista one-dimensional list of items linked lista dynamic list in which the elements are connected by pointer to another element nulla constant value that indicates the end of list self assessment choose the appropriate answer pointers permit the referencing of structures in (anormal way (buniform way (ccommon way (dnone recursive data structure is data structure that has the same form regardless of the (asize of the data (bshape of the data (corigin of the data (dform of the data the insert function takes pointer to an existing list as the (asecond parameter (bthird parameter (cfirst parameter (dnone circular linked list has no (abeginning and no mid point (bend and last (cbeginning and beginning (dbeginning and no end fill in the blanks memory allocation in linked lists is linked list stores two items of informationand an function is used to create the list is list of elements in which the elements of the list can be placed anywhere in memory state whether the following statements are true or false we cannot insert node after any specific node in the single linked list each node provides information about where the previous node is in the list linked list is not recursive data structure lovely professional university |
23,978 | notes review questions write program to sort the elements of linked list why are linked list better than arrayscompare giving examples create linked list and write programs to(ainsert node at the nth position where is accepted as an input from the keyboard (bdelete node from the nth position where is accepted as an input from the keyboard (cshift the node at the nth position to the position where and are accepted as inputs from the keyboard write program for building of an element of the circular linked list describe the method of inserting node using recursive program write program to merge two given lists and to form in the following mannerthe first element of is the first element of and the second element of is the first element of the second elements of and become the third and fourth elements of cand so on if either or gets exhaustedthe remaining elements of the other are to be copied to write program to transform circular list into chain describe adt of singly linked lists write remove for the (secondimplementation of simply linked lists that remembers the last-used position prepare collection of files containing the declarations for contiguous list and all the functions for list processing answersself assessment ( ( ( ( dynamic an element of the lista link or address of another node insert linked list false false false further readings books brian kernighan and dennis ritchiethe programming languageprentice hall data structures and algorithmsshi-kuo changworld scientific lovely professional university |
23,979 | data structures and efficient algorithmsburkhard monienthomas ottmannspringer notes kruse data structure program designprentice hall of indianew delhi mark allen welesdata structure algorithm analysis in second adition addison-wesley publishing rg dromeyhow to solve it by computercambridge university press shi-kuo changdata structures and algorithmsworld scientific sorenson and tremblayan introduction to data structure with algorithms thomas cormencharles eleiserson ronald rivestintroduction to algorithms prentice-hall of india pvt limitednew delhi timothy buddclassic data structures in ++addison wesley online links www en wikipedia org www web-source net www webopedia com lovely professional university |
23,980 | anil sharmalovely professional university unit stacks notes contents objectives introduction stack model implementation of stacks array-based implementation pointer-based implementation applications of stacks maze problem simulating recursive function using stack simulation of factorial summary keywords self assessment review questions further readings objectives after studying this unityou will be able todescribe the stack model explain the implementation and applications of stacks introduction stack is another linear data structure having very interesting property unlike arrays and link listsan element can be inserted and deleted not at any arbitrary position but only at one end thusone end of stack is sealed for insertion and deletion while the other end allows both the operations stack model stack is linear data structure in as much as its member elements are ordered as st ndand last howeveran element can be inserted in and deleted from only one end the other end remains sealed this open end to which elements can be inserted and deleted from is called stack top or top of the stack consequentlythe elements are removed from stack in the reverse order of insertion stack is said to possess lifo (last in first outproperty data structure has lifo property if the element that can be retrieved first is the one that was inserted last lovely professional university |
23,981 | we come across several such structures in our day-to-day life consider pile of plates as shown below notes po push stack of plates clearlyan element can be inserted in stack only on the top and can be retrieved only from the top the following are the operations on stack spush(sethis inserts an element into the stack pop(sae this deletes an element from the stack and stores it in isempty(sae true/false this checks if the stack is empty isfull(sae true/false this checks if the stack is full or not point to remember is that the above three operations are the only ones permitted with which stack could be operated on consider the following stack of integers to understand the stack operations to - to to empty to to to after push after push after pop after push stack full stack operations in pseudo-codestack-empty(sif top[ return true else return false push(sxtop[ <top[ [top[ ]< pop(slovely professional university |
23,982 | notes if stack-empty(sthen error "underflowelse top[ <top[ return [top[ the running time for the operations is ( (constant time implementation of stacks there are two basic methods for the implementation of stacks one where the memory is used statically and the other where the memory is used dynamically array-based implementation in this schemean array of certain maximum size is allocated memory statically ( once for allthe stack and its operations are implemented using this array the following pseudo-code shows the array-based implementation of stack in thisthe elements of the stack are of type struct stk array[max_size]/max_size is the maximum size *int top - /stack top initially given value - *stackvoid push( /*inserts an element into the stack *if (stack top =max_sizeprintf("stack is full-insertion not possible")else stack top stack top stack array[stack topet pop(/*returns the top element from the stack * xif(stack top =- printf("stack is empty")else stack array[stack top]stack top stack top lovely professional university |
23,983 | notes return( )boolean empty(/checks if the stack is empty boolean empty falseif(stack top =- empty true else empty falsereturn(empty)void initialise(/this procedure initializes the stack stack top - the above implementation strategy is easy and fast since it does not have run-time overheads at the same time it is not flexible since it cannot handle situation when the number of elements exceeds max_size alsolet us sayif max_size is derided statically to and stack actually has only elementsthen memory space for the rest of the elements would be wasted task write syntax to declare array in program pointer-based implementation here the memory is used dynamically for every push operationthe memory space for one element is allocated at run-time and the element is inserted into the stack for every pop operationthe memory space for the deleted element is de-allocated and returned to the free space pool hence the shortcomings of the array-based implementation are overcome but sincethis allocates memory dynamicallythe execution is slowed down the stack is implemented as linked list as shown in figure figure implementation of stack using linked list top - nil the following pseudo-code is for the pointer-based implementation of stack each element of the stack is of type struct stk elementlovely professional university |
23,984 | notes struct stk *next}struct stk *stackvoid push(struct stk *pt estruct stk *xx new(stk) element ex next nullp xhere the stack full condition is checked by the call to new which would give an error if no memory space could be allocated pop(struct stk *pstruct stk *xif ( =nullprintf("stack is empty")else px nextreturn( element)boolean empty(sstruct stk *pif ( =nullreturn(true)else return(false)void initialize(struct stk *pp null applications of stacks there are numerous applications of the stack data structure in computer algorithms it is used to store return information in the case of function/procedure/subroutine calls henceone would find stack in architecture of any central processing unit (cpuin this sectionwe would just illustrate few of them lovely professional university |
23,985 | maze problem notes in classical experimentation in psychologya rat is placed through the door of large box in which walls are set up to restrict movements in most directions the rat' movement is observed as it finds outthrough the obstaclesa way to escape from the box two-dimensional version of this problem is easy to formulate where rectangular maze is conceived as consisting of number of unit square rooms such that movement from one square to another is restricted an by maze can be represented by an array maze of size [ nwhere each maze[ ,jrepresents unit room if maze[ ,jis the room may be entered into but it cannot be entered if maze[ ,jis the entrance is at maze[ , and the exit is at maze[ ,nevaluation of expressions one of the biggest technical hurdles faced when conceiving the idea of higher level programming languagesis to generate machine language instructionswhich would properly evaluate any arithmetic expression complex assignment statement such asz - might have several meaningseven if it were uniquely definedby the full use of parenthesis an expression is made up of operandsoperators and delimiters the above expression has five operands xyab and the first problem with understanding the meaning of an expression is to decide in what order the operations are carried out this means that every language must uniquely define such an order to fix the order of evaluation we assign to each operator priority set of sample priorities are as followsoperator (or **unary -unary+![not*/+>=!&|||priority associativity left to right right to left left to right left to right left to right left to right left to right left to right but by using parenthesis we can override these rules and such expressions are always evaluated with the inner most parenthesized expression first the above notation of any expression is called infix notation (in which operators come in between the operandsthe notation is traditional notationwhich needs operator' priorities and associativities but how can compiler accept such an expression and produce correct polish notation or prefix form (in which operators come before operandspolish notation has several advantages over infix notation such asthere is no need for considering priorities while evaluating themthere is no need of introducing parenthesis for maintaining order of execution of operators similarlyreverse polish notation or postfix form also has same advantages over infix notationin this notation operators come after the operands consider the following examples infix prefix postfix + +xy xyx+ * + +yz xyz* + - -+xyz xyz*+lovely professional university |
23,986 | notes stacks are frequently used for converting infix form into equivalent prefix and postfix forms the whole logic is same as for infix to postfix exceptbefore traversing the string reverse it by strrev(function and then process as beforebut instead of printing the expression take output in another stack and then print the stackat last reverses the string str process of conversion strrev (strprefix expression consider the following example infix expression - after reversing it - now apply the logic of infix to postfix conversion and store the output in another stack operator stack output stack now on printing the stack we havea which is prefix expression here is implementation for converting infix into postfix /convert infix expression into corresponding postfix expression */maximum length of the input expression allowed is characters *#include #include #include #include typedef struct char data[ ]/array to hold stack contents *int top/top of the stack pointer *}stk/function prototypes *void initstack(stk *stack)void get_infix(char infix[])void converttopostfix(char infix[]char postfix[])int isoperator(char )int precedence(char operator char operator )int pred_level(char ch)void push(stk *stackchar value) lovely professional university |
23,987 | notes char pop(stk *stack)char stacktop(stk *stack)int isempty(stk *stack)int isfull(stk *stack)void printresult(char infix[]char postfix[])/*void print_msg(void);*/program entry point *int main(voidchar infix[ ]postfix[ ]=""/convert from infix to postfix main function *converttopostfix(infixpostfix)/display the postfix equivalent *infix[strlen(infix)- '\ 'printresult(infixpostfix)return( )void initstack(stk *stack/initalise the stack *stack->top - /stack is initially empty *void get_infix(char infix[]/get infix expression from user *int iprintf("enter infix expression below (max characters excluding spaces\ ")fflush(stdin)for = < /to read in only characters excluding spaces *if (infix[igetchar()='\ni++breakelse if !(isspace(infix[ ]) ++infix[ '\ 'void converttopostfix(char infix[]char postfix[]/convert the infix expression to postfix notation *int ilengthj= lovely professional university |
23,988 | notes char top_chstk stackinitstack(&stack)/initialise stack *get_infix(infix)/get infix expression from user *length strlen(infix)if length /if strlen if infix is more than zero *push(&stack'(')strcat(infix")")length++for = <lengthi+if isdigit(infix[ ]/if current operator in infix is digit *postfix[ ++infix[ ]left else if infix[ ='(parenthesis */if current operator in infix is push(&stack'(')else if isoperator(infix[ ]/if current operator is operator *while( top_ch stacktop(&stack)if top_ch ='\ /get tos */no stack left *printf("\ninvalid infix expression\ ")exit( )else if isoperator(top_chif pred_level(top_ch>pred_level(infix[ ]postfix[ ++pop(&stack)else breakelse lovely professional university |
23,989 | notes breakpush(&stackinfix[ ])else if (infix[ =')'/if current operator is right parenthesis *while ( top_ch stacktop(&stack)/get tos *if top_ch ='\ /no stack left *printf("\ninvalid infix expression\ ")/*print_msg();*exit( )else if top_ch !'(postfix[ ++top_chpop(&stack)else pop(&stack)breakcontinuepostfix[ '\ 'int isoperator(char /determine if is an operator *if ='+| ='-| ='*| ='/| ='%| ='^return lovely professional university |
23,990 | notes else return int pred_level(char ch/determine precedence level *if ch ='+|ch ='-return else if ch ='^return else return int precedence(char operator char operator /determine if the precedence of operator is less thanequal togreater than the precedence of operator *if pred_level(operator pred_level(operator return else if pred_level(operator pred_level(operator return - else return void push(stk *stackchar value/push value on the stack *if !(isfull(stack)(stack->top)++stack->data[stack->topvaluechar pop(stk *stack/pop value off the stack *char chif !(isempty(stack)ch stack->data[stack->top](stack->top)--return chelse return '\ ' lovely professional university |
23,991 | notes char stacktop(stk *stack/return the top value of the stack without popping the stack *if !(isempty(stack)return stack->data[stack->top]else return '\ 'int isempty(stk *stack/determine if stack is empty *if stack->top =- /empty *return else /not empty *return int isfull(stk *stack/determine if stack is full *if stack->top = /full *return else /not full *return void printresult(char infix[]char postfix[]/display the result postfix expression *printf("\ \ ")printf("infix notation /*system("cls");*% \ "infix)printf("postfix notation% \ \ "postfix)here are some results of the test run infix ( + )-( * / )+ - * /( - ( * ^ )-( % - )^ postfix + * /- * -/ ^* % - ^evaluating postfix expression an expression may be evaluated by making left to right scanstacking operands and evaluating operators using the correct number of operands from the stack and finally placing back the result on to the stack lovely professional university |
23,992 | notes exampleto evaluate postfix expressionabc**/de *+ac*the following steps will be executedtop op ii op * op ii op * /( **ca /( ** ( ea+ /( **cd ee* /( **ca/( ** ( * ( *clab exercise here is program that implements the above idea into program #include #include #include #define maxc double eva (charl[])double pop(struct stack *)void push(struct stack *double)int empty(struct stack *)int isdigit(char)double oper(intn doubledouble)void main(char expr[maxc]int position whi ((expr[position++getchar()!'\'expr[--position'\ 'printf("% % ""the original postfix expression is"printf("\ % "eval(expr))struct stack int topdouble data[maxc] lovely professional university expr) |
23,993 | notes double eval (char exp[]int cpositiondouble opnd opnd valuestruct stack opndstkopndstk top - for (position ( expr[position!'\ 'posit on+if (isdigit( )push(&opndstk(double( -' '))else opnd pop(&opndstk)opnd pop(&opndstk)value oper(copnd opnd )push(&opndstkvalue)return(pop(&pndstk))int isdigit(char symbreturn (symb >' &symb <' ')double oper(int symbdouble op double op switch(symbcase '+return (opl op )case '-return (opl op )case '*return (opl op )case '/return (opl op )case '^return (opl op )default printf("% ""illegal operation")double pop(struct stack *sint xif( top =- return( )else lovely professional university |
23,994 | notes tops top - return ( data[ ])void push(struct stack *sdouble eif( top =maxcprintf("stack full!")else top top data[ topeint empty(struct stack *pif( top =- return else return simulating recursive function using stack recursive solution to problem is often more expensive than non-recursive solutionboth in terms of time and space frequentlythis expense is small price to pay for the logical simplicity and self-documentation of the recursive solution howeverin production program (such as compilerfor examplethat may be run thousands of timesthe recurrent expense is heavy burden on the system' limited resources thusa program may be designed to incorporate recursive solution in order to reduce the expense of design and certificationand then carefully converted to non-recursive version to be put into actual day-to-day use as we shall seein performing such as conversion it is often possible to identify parts of the implementation of recursion that are superfluous in particular application and thereby significantly reduce the amount of work that the program must perform suppose that we have the statement rout ( )where route is defined as function by the header rout( ) is referred to as an argument (of the calling function)and is referred to as parameter (of the called functionwhat happens when function is calledthe action of calling function may be divided into three parts passing arguments allocating and initializing local variables transferring control to the function lovely professional university |
23,995 | let us examine each of these three steps in turn passing argumentsfor parameter in ca copy of the argument is made locally within the functionand any changes to the parameter are made to that local copy the effect to this scheme is that the original input argument cannot be altered in this methodstorage for the argument is allocated within the data area of the function allocating and initializing local variablesafter arguments have been passedthe local variables of the function are allocated these local variables include all those declared directly in the function and any temporaries that must be created during the course of execution transferring control to the functionat this point control may still not be passed to the function because provision has not yet been made for saving the return address if function is given controlit must eventually restore control to the calling routine by means of branch howeverit cannot execute that branch unless it knows the location to which it must return since this location is within the calling routine and not within the functionthe only way that the function can know this address is to have it passed as an argument this is exactly what happens aside from the explicit arguments specified by the programmerthere is also set of implicit arguments that contain information necessary for the function to execute and return correctly chief among these implicit arguments is the return address the function stores this address within its own data area when it is ready to return control to the calling programthe function retrieves the return address and branches to that location once the arguments and the return address have been passedcontrol may be transferred to the functionsince everything required has been done to ensure that the function can operate on the appropriate data and then return to the calling routine safely notes return from function when function returnsthree actions are performed firstthe return address is retrieved and stored in safe location secondthe function' data area is freed this data area contains all local variables (including local copies of arguments)temporariesand the return address finallya branch is taken to the return addresswhich had been previously saved this restores control to the calling routine at the point immediately following the instruction that initiated the call in additionif the function returns valuethat value is placed in secure location from which the calling program may retrieve it usually this location is hardware register that is set-aside for this purpose task discuss maze problem simulation of factorial let us look at the factorial function as recursion example we present the code for that functionincluding temporary variables explicitly and omitting the test for negative inputas followsint fact(int nint xyif ( = return( ) -ly fact( )lovely professional university |
23,996 | notes return ( )how are we to define the data area for this functionit must contain the parameter and the local variables and as we shall seeno temporary variables are needed the data area must also contain return address in this casethere are two possible points to which we might want to returnthe assignment of fact(xto yand the main program that called fact suppose that we had two labels and that we let the label label be the label of section of code label resultwithin the simulating program let the label be the label of statement label return(result)this reflects convention that the variable to result contains the value to be returned by an invocation of the fact function the return address will be stored as an integer (equal to either or to effect return from recursive call the statement switch(icase goto label case goto abe is executed thusif return is executed to the main program that called factand if = return is simulated to the assignment of the returned value to the variable in the previous execution of fact proving correctness of parenthesis in an expression lab exercise this program takes one mathematical expression and checks whether the opening and closing parenthesis match or not #define leftbracket '{#define rightbracket '}#include main(char *pexpr[ ]printf("enter an expression :")scanf("% ",expr) =exprwhile( !'\ 'if* =leftbracketpush( )if(* =rightbrackett=pop()if( (printf("error:")) ++ lovely professional university |
23,997 | if(isempty()print("statement is parenthetically balanced")notes else print("statement is parenthetically unbalanced")lab exercise the program given below implements the stack data structure using an array in this program the elements are pushed into array stackthrough pushfunction the parameters passed to pushare the base address of the arraythe position in the stack at which the element is to be placed and the element itself care is taken by the pushfunction that the user does not try to place the element beyond the bounds of the stack this is done by checking the value stored in pos popfunction pops out the last element stored in the stack]becausepos holds the position which has the last element in the stack /to pop and push items in stack *#define max void push int int popint stack[maxint pos void mainint clrscrpos - /stack is empty *push push push push popprintf "\nitem popped out is % " popprintf "\nitem popped out is % " /pushes item on the stack *void push int data if pos =max printf "\nstack is fullelse pos+stackpos data lovely professional university |
23,998 | notes /pops off the items from the stack *int popint data if pos =- printf "\nstack is emptyreturn - else data stackpos pos-return data in this program stack is implemented and maintained using linked list this implementation is more sophisticated compared to the one that uses an arraythe added advantage being we can push as many elements as we want new node is created by push(using malloc)every time an element is pushed in the stack each node in the linked list contains two membersdata holding the data and link holding the address of the next node the end of the stack is identified by the node holding null in its link part the popfunction pops out the last element inserted in the stack and frees the memory allocated to hold it stack_displaydisplays all the elements that stack holds countcounts and returns the number of elements present in the stack #include "alloc hstruct node int data struct node *link push struct node **int pop struct node *mainstruct node *top /top will always point to top of stack *int itemtop null /empty stack *push &top push &top push &top push &top push &top lovely professional university |
23,999 | notes push &top push &top clrscrstack_display top printf "no of items in stack %dcount top printf "\nitems extracted from stack item pop &top printf "% "item item pop &top printf "% "item item pop &top printf "% "item stack_display top printf "no of items in stack %dcount top /adds new element on the top of stack *push struct node **sint item struct node * malloc sizeof struct node -data item -link * * /removes an element from top of stack *pop struct node ** int item struct node * /if stack is empty *if * =null printf stack is emptyelse * item -data * -link free return item /displays whole of the stack *stack_display struct node * lovely professional university |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.