1 / 59

DATA STRUCTURE

DATA STRUCTURE. SUBMUTTED BY:- SANJEEV KUMAR Lecturer in computer engg. G.P. LOHARU(BHIWANI). ARRAY. Arrays. An array is a collection of data elements that are of the same type (e.g., a collection of integers, collection of characters, collection of doubles). Arrays. 1-dimensional array.

fullers
Download Presentation

DATA STRUCTURE

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. DATA STRUCTURE SUBMUTTED BY:- SANJEEV KUMAR Lecturer in computer engg. G.P. LOHARU(BHIWANI)

  2. ARRAY

  3. Arrays • An array is a collection of data elements that are of the same type (e.g., a collection of integers, collection of characters, collection of doubles).

  4. Arrays • 1-dimensional array. • 3-dimensional array (3rd dimension is the day). Oct 14 Oct 15 Oct 16

  5. Array Applications • Given a list of test scores, determine the maximum and minimum scores. • Read in a list of student names and rearrange them in alphabetical order (sorting). • Given the height measurements of students in a class, output the names of those students who are taller than average.

  6. Array Declaration • Syntax: <type> <arrayName>[<array_size>] Ex. int Ar[10]; • The array elements are all values of the type <type>. • The size of the array is indicated by <array_size>, the number of elements in the array. • <array_size> must be an int constant or a constant expression. Note that an array can have multiple dimensions.

  7. 0 1 2 3 4 5 6 7 8 9 Ar -- -- -- -- -- -- -- -- -- -- Array Declaration // array of 10 uninitialized ints int Ar[10]; 0 1 3 4 2 5

  8. Subscripting • Declare an array of 10 integers: int Ar[10]; // array of 10 ints • To access an individual element we must apply a subscript to array named Ar. • A subscript is a bracketed expression. • The expression in the brackets is known as the index. • First element of array has index 0. Ar[0] • Second element of array has index 1, and so on. Ar[1], Ar[2], Ar[3],… • Last element has an index one less than the size of the array. Ar[9] • Incorrect indexing is a common error.

  9. -- 1 -- -- -- -- 0 1 2 3 4 5 6 7 8 9 Ar -- -- -- 1 -- -- -- -- -- -- Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8] Ar[9] Subscripting // array of 10 uninitialized ints int Ar[10]; Ar[3] = 1; int x = Ar[3];

  10. 0 1 2 3 4 5 6 7 8 9 Ar 9 8 7 6 5 4 3 2 1 0 -1 6 0 1 2 3 4 5 6 7 8 9 Ar 9 8 7 -1 5 4 3 2 1 0 Array Initialization Ex. 4 int Ar[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; Ar[3] = -1;

  11. Program with Arrays int main() { int values[5]= {11,1,3,6,10}; for (int i = 1; i < 5; i++) { values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4]; }

  12. Stack Overview • Stack • Basic operations of stack • Pushing, popping etc. • Implementations of stacks using • array • linked list

  13. The Stack • A stack is a list with the restriction • that insertions and deletions can only be performed at the top of the list • The other end is called bottom • Fundamental operations: • Push: Equivalent to an insert • Pop: Deletes the most recently inserted element • Top: Examines the most recently inserted element

  14. Stacks are less flexible • but are more efficient and easy to implement • Stacks are known as LIFO (Last In, First Out) lists. • The last element inserted will be the first to be retrieved

  15. A A B A top top top Push and Pop • Primary operations: Push and Pop • Push • Add an element to the top of the stack • Pop • Remove the element at the top of the stack empty stack push an element push another pop top

  16. Implementation of Stacks • Any list implementation could be used to implement a stack • Arrays (static: the size of stack is given initially) • Linked lists (dynamic: never become full) • We will explore implementations based on array and linked list • Let’s see how to usean array to implement a stack first

  17. Array Implementation • Need to declare an array size ahead of time • Associated with each stack is TopOfStack • for an empty stack, set TopOfStack to -1 • Push • (1)   Increment TopOfStack by 1. • (2)   Set Stack[TopOfStack] = X • Pop • (1)   Set return value to Stack[TopOfStack] • (2)   Decrement TopOfStack by 1 • These operations are performed in very fast constant time

  18. Push Stack • void Push(constdouble x); • Push an element onto the stack • If the stack is full, print the error information. • Note top always represents the index of the top element. After pushing an element, increment top. void Stack::Push(constdouble x) { if (IsFull()) cout << "Error: the stack is full." << endl; else values[++top] = x; }

  19. Pop Stack • double Pop() • Pop and return the element at the top of the stack • If the stack is empty, print the error information. (In this case, the return value is useless.) • Don’t forgot to decrement top double Stack::Pop() { if (IsEmpty()) { cout << "Error: the stack is empty." << endl; return -1; } else { return values[top--]; } }

  20. Stack Top • double Top() • Return the top element of the stack • Unlike Pop, this function does not remove the top element double Stack::Top() { if (IsEmpty()) { cout << "Error: the stack is empty." << endl; return -1; } else return values[top]; }

  21. Queue Overview • Queue • Basic operations of queue • Enqueuing, dequeuing etc. • Implementation of queue • Array • Linked list

  22. Queue • Like a stack, a queue is also a list. However, with a queue, insertion is done at one end, while deletion is performed at the other end. • Accessing the elements of queues follows a First In, First Out (FIFO) order. • Like customers standing in a check-out line in a store, the first customer in is the first customer served.

  23. Enqueue and Dequeue • Primary queue operations: Enqueue and Dequeue • Like check-out lines in a store, a queue has a front and a rear. • Enqueue • Insert an element at the rear of the queue • Dequeue • Remove an element from the front of the queue Insert (Enqueue) Remove(Dequeue) front rear

  24. Implementation of Queue • Just as stacks can be implemented as arrays or linked lists, so with queues. • Dynamic queues have the same advantages over static queues as dynamic stacks have over static stacks

  25. List Overview • Linked lists • Basic operations of linked lists • Insert, find, delete, print, etc. • Variations of linked lists • Doubly linked lists

  26. A C B A Linked Lists • A linked list is a series of connected nodes • Each node contains at least • A piece of data (any type) • Pointer to the next node in the list • Head: pointer to the first node • The last node points to NULL  Head node data pointer

  27. A Simple Linked List Class • We use two classes: Node and List • Declare Node class for the nodes • data: double-type data in this example • next: a pointer to the next node in the list class Node { public: double data; // data Node* next; // pointer to next };

  28. A Simple Linked List Class • Declare List, which contains • head: a pointer to the first node in the list. Since the list is empty initially, head is set to NULL • Operations on List class List { public: List(void) { head = NULL; } // constructor ~List(void); // destructor bool IsEmpty() { return head == NULL; } Node* InsertNode(int index, double x); int FindNode(double x); int DeleteNode(double x); void DisplayList(void); private: Node* head; };

  29. A Simple Linked List Class • Operations of List • IsEmpty: determine whether or not the list is empty • InsertNode: insert a new node at a particular position • FindNode: find a node with a given value • DeleteNode: delete a node with a given value • DisplayList: print all the nodes in the list

  30. Inserting a new node • Node* InsertNode(int index, double x) • Insert a node with data equal to x after the index’thelements. (i.e., when index = 0, insert the node as the first element; when index = 1, insert the node after the first element, and so on) • If the insertion is successful, return the inserted node. Otherwise, return NULL. (If index is < 0 or > length of the list, the insertion will fail.) • Steps • Locate index’th element • Allocate memory for the new node • Point the new node to its successor • Point the new node’s predecessor to the new node index’th element newNode

  31. Inserting a new node • Possible cases of InsertNode • Insert into an empty list • Insert in front • Insert at back • Insert in middle • But, in fact, only need to handle two cases • Insert as the first node (Case 1 and Case 2) • Insert in the middle or at the end of the list (Case 3 and Case 4)

  32. Deleting a node • int DeleteNode(double x) • Delete a node with the value equal to x from the list. • If such a node is found, return its position. Otherwise, return 0. • Steps • Find the desirable node (similar to FindNode) • Release the memory occupied by the found node • Set the pointer of the predecessor of the found node to the successor of the found node • Like InsertNode, there are two special cases • Delete first node • Delete the node in middle or at the end of the list

  33. A C B Variations of Linked Lists • Circular linked lists • The last node points to the first node of the list • How do we know when we have finished traversing the list? (Tip: check if the pointer of the current node is equal to the head.) Head

  34. A C B Variations of Linked Lists • Doubly linked lists • Each node points to not only successor but the predecessor • There are two NULL: at the first and last nodes in the list • Advantage: given a node, it is easy to visit its predecessor. Convenient to traverse lists backwards   Head

  35. Array versus Linked Lists • Linked lists are more complex to code and manage than arrays, but they have some distinct advantages. • Dynamic: a linked list can easily grow and shrink in size. • We don’t need to know how many nodes will be in the list. They are created in memory as needed. • In contrast, the size of a C++ array is fixed at compilation time. • Easy and fast insertions and deletions • To insert or delete an element in an array, we need to copy to temporary variables to make room for new elements or close the gap caused by deleted elements. • With a linked list, no need to move other nodes. Only need to reset some pointers.

  36. Trees and Binary Trees Become Rich Force Others to be Poor Stock Fraud Rob Banks The class notes are a compilation and edition from many sources. The instructor does not claim intellectual property or ownership of the lecture notes.

  37. Computers”R”Us Sales Manufacturing R&D US International Laptops Desktops Europe Asia Canada What is a Tree • A tree is a finite nonempty set of elements. • It is an abstract model of a hierarchical structure. • consists of nodes with a parent-child relation. • Applications: • Organization charts • File systems • Programming environments

  38. A D B C E G H F K I J Tree Terminology • Subtree: tree consisting of a node and its descendants • Root: node without parent (A) • Siblings: nodes share the same parent • Internal node: node with at least one child (A, B, C, F) • External node (leaf ): node without children (E, I, J, K, G, H, D) • Ancestors of a node: parent, grandparent, grand-grandparent, etc. • Descendant of a node: child, grandchild, grand-grandchild, etc. • Depth of a node: number of ancestors • Height of a tree: maximum depth of any node (3) • Degree of a node: the number of its children • Degree of a tree: the maximum number of its node. subtree

  39. A B C D E F G H I Tree Properties PropertyValue Number of nodes Height Root Node Leaves Interior nodes Ancestors of H Descendants of B Siblings of E Right subtree of A Degree of this tree

  40. Data Data Data Data Data Data Data            Trees • Every tree node: • object – useful information • children – pointers to its children

  41. B    A D F B A D F   C E C E A Tree Representation • A node is represented by an object storing • Element • Parent node • Sequence of children nodes

  42. Data A B C D I H G F E J K L Left Child Right Sibling Left Child, Right Sibling Representation

  43. Tree Traversal • Two main methods: • Preorder • Postorder • Recursive definition • Preorder: • visit the root • traverse in preorder the children (subtrees) • Postorder • traverse in postorder the children (subtrees) • visit the root

  44. 1 Become Rich 2 5 9 1. Motivations 2. Methods 3. Success Stories 3 6 7 8 4 1.1 Enjoy Life 1.2 Help Poor Friends 2.1 Get a CS PhD 2.2 Start a Web Site 2.3 Acquired by Google Preorder Traversal AlgorithmpreOrder(v) visit(v) foreachchild w of v preorder (w) • A traversal visits the nodes of a tree in a systematic manner • In a preorder traversal, a node is visited before its descendants • Application: print a structured document

  45. 9 cs16/ 8 3 7 todo.txt1K homeworks/ programs/ 4 5 6 1 2 Robot.java20K h1c.doc3K h1nc.doc2K DDR.java10K Stocks.java25K Postorder Traversal AlgorithmpostOrder(v) foreachchild w of v postOrder (w) visit(v) • In a postorder traversal, a node is visited after its descendants • Application: compute space used by files in a directory and its subdirectories

  46. Binary Tree • Applications: • arithmetic expressions • decision processes • searching • A binary tree is a tree with the following properties: • Each internal node has at most two children (degree of two) • The children of a node are an ordered pair • We call the children of an internal node left child and right child • Alternative recursive definition: a binary tree is either • a tree consisting of a single node, OR • a tree whose root has an ordered pair of children, each of which is a binary tree A C B D E F G I H

  47. Skewed Binary Tree A A Complete Binary Tree A 1 B B B C C 2 F G D E D 3 E H I 5 4 Examples of the Binary Tree

  48. A A B B Differences Between A Tree and A Binary Tree • The subtrees of a binary tree are ordered; those of a tree are not ordered. • Are different when viewed as binary trees. • Are the same when viewed as trees.

  49. D C A B E   B A D     C E Data Structure for Binary Trees • A node is represented by an object storing • Element • Parent node • Left child node • Right child node

  50. Maximum Number of Nodes in a Binary Tree • The maximum number of nodes on depth i of a binary tree is 2i, i>=0. • The maximum nubmer of nodes in a binary tree of height k is 2k+1-1, k>=0. Prove by induction.

More Related