Popping Items Off a Stack Using a Function Lesson xx

Slides:



Advertisements
Similar presentations
Doubly linked list concept Node structure Insertion sort Insertion sort program with a doubly linked list.
Advertisements

1 Stacks Chapter 4. 2 Objectives You will be able to: Describe a stack as an ADT. Build a dynamic-array-based implementation of stacks. Build a linked-list.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Lesson 9 Pointers CS 1 Lesson 9 -- John Cole1. Pointers in Wonderland The name of the song is called ‘Haddock’s Eyes’.” “Oh, that’s the name of the song,
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Data Structures (part 2). Stacks An Everyday Example Your boss keeps bringing you important items to deal with and keeps saying: “Put that last ‘rush’
Review the following : Flowcharting Variable declarations Output Input Arithmetic Calculations Conditional Statements Loops.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
1 Working with Pointers An exercise in destroying your computer.
Chapter 16 – Data Structures and Recursion. Data Structures u Built-in –Array –struct u User developed –linked list –stack –queue –tree Lesson 16.1.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
 Memory setup  Pointer declaration  Address operator  Indirection  Printing addresses or pointers.
 Memory from the heap  Dynamic memory allocation using the new operator  Build a dynamic linked list  Another way of traversing a linked list 
 Review building a complete linked list  List traversal in main ( )  List traversal using a function.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Lesson xx Why use functions Program that needs a function Function header Function body Program rewritten using a function.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
  A linked list is a collection of components called nodes  Every node (except the last one) contains the address of the next node  The address of.
1 Data Structures CSCI 132, Spring 2016 Notes_ 5 Stacks.
STACKS & QUEUES for CLASS XII ( C++).
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Pointers and Linked Lists
Chapter 12 – Data Structures
Pointers and Linked Lists
Chapter 1.2 Introduction to C++ Programming
Copy Constructor / Destructors Stacks and Queues
Chapter 9: Pointers.
Two-Dimensional Arrays Lesson xx
Doubly Linked List Review - We are writing this code
Linked lists.
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
void Pointers Lesson xx
Pointers and Linked Lists
CSC 253 Lecture 8.
Arrays & Functions Lesson xx
Returning Structures Lesson xx
CSC 253 Lecture 8.
Linked List Lesson xx   In this presentation, we introduce you to the basic elements of a linked list.
One-Dimensional Array Introduction Lesson xx
File I/O with Records Lesson xx
Passing Structures Lesson xx
Chapter 9: Pointers.
Popping Items Off a Stack Lesson xx
Pointers and Linked Lists
Value returning Functions
Pointers, Dynamic Data, and Reference Types
Arrays Kingdom of Saudi Arabia
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Pointer to Structures Lesson xx
Programming Abstractions
Functions Pass By Value Pass by Reference
Dynamic Memory A whole heap of fun….
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Stacks and Queues Prof. Michael Tsai 2017/02/21.
Pointers & Dynamic Data Structures
Arrays an array of 5 ints is filled with 3,2,4,1,7
Arrays Arrays A few types Structures of related data items
Pointers and dynamic objects
List Iterator Implementation
The Stack.
Linked lists.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Pointers, Dynamic Data, and Reference Types
4.1 Introduction Arrays A few types Structures of related data items
Data Structures & Programming
Presentation transcript:

Popping Items Off a Stack Using a Function Lesson xx In the last module, we learned how to build a dynamic stack and pop items off in main(). This module is about popping items using a function.

Objectives Popping items off a stack in a function Passing a pointer to a function Returning a pointer from a function Our goal in this presentation is to show you how to pop an item off the stack in a function. As an added attraction we will learn about passing pointers to a function and returning a pointer from a function.

Definition of Pop Popping means we take the contents of the first node and store it somewhere for processing. When you pop something off the stack, it implies that the 1st node is to be deleted The second node is then the new head of the list. Popping means we take the contents of the first node and store it somewhere for processing. When you pop something off the stack, it implies that the 1st node is to be deleted. The second node is then the new head of the list.  

Program Definition Write a program that will build a stack. When the user enters a number, create a node and push it onto the top of the stack. The user may enter as many numbers as they wish. The user signifies the end of input by typing the letter ‘s’ for “stop. After the stack is built, pop the first item of the stack into x using a function. Now, let’s write a program to build a stack. When the user enters a number, create a node and push it onto the top of the stack. The user may enter as many numbers as they wish. The user signifies the end of input by typing the letter ‘s’ for “stop”. After the stack is built pop the first item of the stack into x.

Listing of Popping Program Part 1 #include <iostream> using std::cin; using std::cout; using std::endl; #include <cstdlib> struct entry {   int value;   entry* next; }; void printList(const entry*); // prototype entry* pop (entry * h); int main() {   char str[15];   entry* head = 0; // initially empty list   while(1) // create nodes   {     cout << "enter a value (s = stop) “;     cin >> str;     if (str[0] == 's')       break;     entry* temp = new entry; // dynamic memory allocation     temp->value = atoi(str);     temp->next = head; // put new node at front of list     head = temp; // denote new node as new head of list   }   printList(head); // print list   This is the code for the 1st part of the program which builds the stack. The while (1) loop allows the user to create a stack that is any size. When the user presses the ‘s’ key, input is terminated. It is the same as the previous module on popping except that we have a prototype for our pop() function. It is highlighted for you in red.

Listing of Popping Program Part 2 // remove the head of the list (popping) int x; head = pop (head, &x); // call to the pop function printList(head); // print after popping return 0; } entry* pop (entry* h, int * a) { if (h)   { *a = h->value; //indirectly put value in x     entry* n = h->next;     delete h;     h = n;   }   return h; } void printList(const entry* h) {   for (const entry* p = h; p; p = p->next)     cout << p->value << endl; } This is the 2nd part of the code to pop the 1st node into x. The call to function pop() is highlighted in red and so is the listing of function pop(). Afterwards, we print the stack to verify that the 1st node was popped off. Let’s go through the program now.

Stack Building Code Output from printList char str[15];   entry* head = 0; // initially empty list   while(1) // create nodes   {     cout << "enter a value (s = stop) “;     cin >> str;     if (str[0] == 's')       break;     entry* temp = new entry; // dynamic memory allocation     temp->value = atoi(str);     temp->next = head; // put new node at front of list     head = temp; // denote new node as new head of list   } f3c head (76c) 2fe 55 44 (f3c) 4af 88b 33 (4af) 76c 22 11 (2fe) (88b) We have listed the stack building code for you. The picture shows you the stack after the user has entered 5 #s. At the bottom, we have listed the output of the printList() function. All this code was explained in the previous module if you need a review. Output from printList node address: f3c value 55 next 2fe node address: 2fe value 44 next 4af node address: 4af value 33 next 88b node address: 88b value 22 next 76c node address: 76c value 11 next 0

Call to Function Pop f3c head (76c) 2fe 55 44 (f3c) 4af 88b 33 (4af) int x; head = pop (head, &x); // call to the pop function entry* pop (entry* h, int * a) f3c head (76c) 2fe 55 44 (f3c) 4af 88b 33 (4af) 76c 22 11 (2fe) (88b) Here is the picture when you call function pop(). Head is passed into the variable h and the address of x is passed into the pointer a. h points to the node to be popped and a points to x. 55d h f3c x a (55d)

Inside Function Pop( ) Indirectly Put Top of Stack in x entry* pop (entry* h, int * a) { if (h)   { *a = h->value; //indirectly put value in x     entry* n = h->next;     delete h;     h = n;   }   return h; } f3c head (76c) 2fe 55 44 (f3c) 4af 88b 33 (4af) 76c 22 11 (2fe) (88b) x 55d a (55d) The 1st statement in the pop function is if (h). Here we are making sure that the stack has something in it. We don’t want pop off something if the list is empty. The 1st statement inside the if is: *a = h->value; This is how we indirectly store the contents of the first node in x. Look at it this way, *a = h->value means: in the variable pointed to by a, store what is in h->value. a is pointing to x and h->value is 55, therefore, the # 55 is stored in to x. h

Inside Function Pop( ) Point to 2nd Node, Delete 1st Node (1) *a = h->value; (2)    entry* n = h->next; (3)    delete h; (4)    h = n; f3c head 2fe (76c) 55 44 (f3c) 4af 88b 33 (4af) 76c 22 11 (2fe) (88b) 2 n Now, that we have the contents of the 1st node in x, consider this step 1, let’s look at the remaining code inside of the if . For step 2, we need to set up a pointer called n and make it point to the second node. This is accomplished with the statement: entry*n = h->next; In step 3, we need to release the memory occupied by the 1st node with delete h;. 3 f3c 55 55d h x a 1 (55d)

Inside Function Pop( ) Make h Point to 2nd Node (1) *a = h->value; (2)    entry* n = h->next; (3)    delete h; (4)    h = n; head 2 f3c 2fe n (f3c) (2fe) (4af) (88b) (76c) 44 4af 33 88b 22 76c 11 After we have completed steps 1-3 the first node is gone. For step 4, we make h point to the second node with the statement h = n; Now, h has the address of the 2nd node which is 2fe. As you can see from our picture, back in main() head is pointing to a non-existent node because we deleted it in step 3. Not to worry. 4 2fe 55 55d h x a 1 (55d)

Returning a Pointer From Pop( ) (5) return h; 2fe head (76c) 44 4af 88b 33 (4af) 76c 22 11 (2fe) (88b) 2 n 5 The very last statement of the pop function is: return h; This will take what is in h and put it in head in main(). We have labeled this as step 5. In our picture, head is pointing to the 2nd node. This is an example of returning a pointer from a function 4 2fe 55 55d h x a 1 (55d)

After Call to Pop( ) Function 2fe head (76c) 44 4af 88b 33 (4af) 76c 22 11 (2fe) (88b) When you exit function pop(), all the local variable disappear and your picture will look as follows back in main() : head will point to the original 2nd node and x will contain the # 55. The red indicates the operations that happened in function pup. There you have popping the 1st node into x. The last operation that we performed in this program is to call the printList() function to verify that the first node was indeed popped off. 55 x (55d)

Summary Popping items off a stack in a function Passing a pointer to a function Returning a pointer from a function In this presentation, we reviewed building a dynamic stack. We also learned about popping items off a stack in a function. As a side benefit, we saw how pointers are passed to functions and a use for returning a pointer. In the next modules we’ll put these data structures such as queues and stacks to use.