Download presentation
Presentation is loading. Please wait.
Published byFarida Tan Modified over 6 years ago
1
DATA STRUCTURE SUBMUTTED BY:- MADHU MADHAN Lecturer in computer engg. G.P. MEHAM (ROHTAK)
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
Array Declaration // array of 10 uninitialized ints int Ar[10]; -- Ar
4 5 6 3 2 8 9 7 1 1 2 3 4 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
Subscripting // array of 10 uninitialized ints int Ar[10]; Ar[3] = 1; int x = Ar[3]; 1 -- -- 1 Ar 4 5 6 3 2 8 9 7 Ar[4] Ar[5] Ar[6] Ar[3] Ar[0] Ar[2] Ar[8] Ar[9] Ar[7] Ar[1]
10
Array Initialization Ex. 4
int Ar[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; Ar[3] = -1; 8 7 6 9 Ar 4 3 2 5 1 6 -1 8 7 -1 9 Ar 4 3 2 5 1 6
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
Push and Pop Primary operations: Push and Pop Push Pop
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 B top top A A A 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 use an 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(const double 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(const double 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 Implementation 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
Linked Lists A linked list is a series of connected nodes
B C Head 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 node A 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) Steps
Insert a node with data equal to x after the index’th elements. (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 Steps Like InsertNode, there are two special cases
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
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.) A B C Head
34
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 A B C 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 Rob Banks
Stock Fraud 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
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 Computers”R”Us Sales R&D Manufacturing Laptops Desktops US International Europe Asia Canada
38
Tree Terminology subtree
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. A B D C G H E F I J K subtree
39
Tree Properties Property Value 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 A B C D G E F I H
40
Trees Every tree node: object – useful information
children – pointers to its children Data Data Data Data Data Data Data
41
A Tree Representation B D A C E F
A node is represented by an object storing Element Parent node Sequence of children nodes B A D F C E B D A C E F
42
Left Child, Right Sibling Representation
Data Left Child Right Sibling A B C D E F G H I J K L
43
Tree Traversal Two main methods: Recursive definition Preorder:
Postorder Recursive definition Preorder: visit the root traverse in preorder the children (subtrees) traverse in postorder the children (subtrees)
44
Preorder Traversal Algorithm preOrder(v) visit(v)
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 Algorithm preOrder(v) visit(v) for each child w of v preorder (w) Become Rich 1. Motivations 3. Success Stories 2. Methods 2.1 Get a CS PhD 2.2 Start a Web Site 1.1 Enjoy Life 1.2 Help Poor Friends 2.3 Acquired by Google 1 2 3 5 4 6 7 8 9
45
Postorder Traversal Algorithm postOrder(v) for each child w of v
In a postorder traversal, a node is visited after its descendants Application: compute space used by files in a directory and its subdirectories Algorithm postOrder(v) for each child w of v postOrder (w) visit(v) cs16/ homeworks/ todo.txt 1K programs/ DDR.java 10K Stocks.java 25K h1c.doc 3K h1nc.doc 2K Robot.java 20K 9 3 1 7 2 4 5 6 8
46
Binary Tree 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 Applications: arithmetic expressions decision processes searching A B C D E F G H I
47
Examples of the Binary Tree
Skewed Binary Tree E C D 5 A B C G E I D H F Complete Binary Tree 1 2 3 4
48
Differences Between A Tree and A Binary Tree
The subtrees of a binary tree are ordered; those of a tree are not ordered. A B A B Are different when viewed as binary trees. Are the same when viewed as trees.
49
Data Structure for Binary Trees
A node is represented by an object storing Element Parent node Left child node Right child node B A D C E B D A C E
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.
51
Full Binary Tree Height 3 full binary tree.
A full binary tree of a given height k has 2k+1–1 nodes. Height 3 full binary tree.
52
Node Number Properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Parent of node i is node i / 2, unless i = 1. Node 1 is the root and has no parent.
53
Labeling Nodes In A Full Binary Tree
Label the nodes 1 through 2k+1 – 1. Label by levels from top to bottom. Within a level, label from left to right. 1 2 3 4 6 5 7 8 9 10 11 12 13 14 15
54
Node Number Properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Left child of node i is node 2i, unless 2i > n, where n is the number of nodes. If 2i > n, node i has no left child.
55
Node Number Properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Right child of node i is node 2i+1, unless 2i+1 > n, where n is the number of nodes. If 2i+1 > n, node i has no right child.
56
Full binary tree of depth 3
Complete Binary Trees A labeled binary tree containing the labels 1 to n with root 1, branches leading to nodes labeled 2 and 3, branches from these leading to 4, 5 and 6, 7, respectively, and so on. A binary tree with n nodes and level k is complete iff its nodes correspond to the nodes numbered from 1 to n in the full binary tree of level k. 1 2 3 7 5 11 4 10 6 9 8 15 14 13 12 Full binary tree of depth 3 1 2 3 7 5 9 4 8 6 Complete binary tree
57
Binary Tree Traversals
Let l, R, and r stand for moving left, visiting the node, and moving right. There are six possible combinations of traversal lRr, lrR, Rlr, Rrl, rRl, rlR Adopt convention that we traverse left before right, only 3 traversals remain lRr, lrR, Rlr inorder, postorder, preorder
58
Inorder Traversal Algorithm inOrder(v) if isInternal (v)
In an inorder traversal a node is visited after its left subtree and before its right subtree Algorithm inOrder(v) if isInternal (v) inOrder (leftChild (v)) visit(v) inOrder (rightChild (v)) 3 1 2 5 6 7 9 8 4
59
THANK YOU
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.