day17 - Data Structures: Stacks and Queues (Day 17) Before...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Before introducing new material, here are the recursive versions of the algorithms from the linked list notes (Day 15). Stacks A stack is a collection of items into which new items are inserted and from which items are deleted from only one end, called the top of the stack. Different implementations are possible; although the concept of a stack is unique. Example: Trays in the cafeteria. Stacks and Queues - 1 Data Structures: Stacks and Queues (Day 17) Practice: Create a recursive version of this function to create a linked list from an array of values. Answer will appear in the next set of notes. Practice: Create a recursive version of this function to count the nodes in a linked list. Answer will appear in the next set of notes. //Copies the contents of an array into a dynamically //growing list. struct node *array_to_list (int a[ ], int j, int n) { struct node *head; if ( j >= n) //base case return NULL; else { head = malloc(sizeof(struct node)); head -> data = a[j]; head ->next = array_to_list(a, j+1, n); return head; } } //Count the number of nodes in a list int count(struct node *head) { if (head == NULL) //base case return 0; else return (1 + count(head->next)); } A B C D E F G top
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
There are two primary operations defined on a stack: o push : add a new item to the top of the stack. o pop : removes the item from the top of the stack. A stack is also known as a push-down list. The “access policy” of a stack is LIFO ( L ast I n F irst O ut). A stack is a dynamic structure. It changes as elements are added to and removed from it. pop push A stack can be implemented as a constrained version of a linked list. A stack is referenced via a pointer to the top element of the stack. The link member in the last node of the stack is set to NULL to indicate the bottom of the stack. Example:
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This document was uploaded on 06/12/2011.

Page1 / 8

day17 - Data Structures: Stacks and Queues (Day 17) Before...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online