Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Linked Lists.
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Singly Linked List BTECH, EE KAZIRANGA UNIVERSITY.
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
Module R2 Overview. Process queues As processes enter the system and transition from state to state, they are stored queues. There may be many different.
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
1 Stack and Queue. 2 Stack In Out ABCCB Data structure with Last-In First-Out (LIFO) behavior.
 A queue is a waiting line…….  It’s in daily life:-  A line of persons waiting to check out at a supermarket.  A line of persons waiting.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 18 Stacks.
1 Queues and Lists. QUEUES Very similar to stacks The only difference between them is in the order in which elements are processed. A stack uses a last-in/first-out.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
1 Data Structures  We can now explore some advanced techniques for organizing and managing information  Chapter 12 of the book focuses on: dynamic structures.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 18: Stacks and.
1 Stack Data : a collection of homogeneous elements arranged in a sequence. Only the first element may be accessed Main Operations: Push : insert an element.
Stacks, Queues, and Deques
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Linked List Spring 2013Programming and Data Structure1.
Reference: Vinu V Das, Principles of Data Structures using C and C++
Implementation of Linked List For more notes and topics visit: eITnotes.com.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
Lists 1. Introduction Data: A finite sequence of data items. Operations: Construction: Create an empty list Empty: Check if list is empty Insert: Add.
1 CSE 1342 Programming Concepts Lists. 2 Basic Terminology A list is a finite sequence of zero or more elements. –For example, (1,3,5,7) is a list of.
Cosc237/data structures1 Data Types Every data type has two characteristics: 1.Domain - set of all possible values 2.set of allowable operations Built-in.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
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’
Chapter 1 Object Oriented Programming. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
Stacks And Queues Chapter 18.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Programming Practice 3 - Dynamic Data Structure
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 18: Stacks and Queues.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
1 Queues and Lists. QUEUES Very similar to stacks The only difference between them is in the order in which elements are processed. A stack uses a last-in/first-out.
Data Structures David Kauchak cs302 Spring Data Structures What is a data structure? Way of storing data that facilitates particular operations.
1 Midterm 1 on Friday February 12 Closed book, closed notes No computer can be used 50 minutes 4 questions Write a function Write program fragment Explain.
Data Structure & Algorithms
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
Lecture 10 b Stacks b Queues. 2 Stacks b A stack ADT is linear b Items are added and removed from only one end of a stack b It is therefore LIFO: Last-In,
LINKED LISTS.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
 In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
STACKS & QUEUES for CLASS XII ( C++).
Queues Chapter 4.
Chapter 12 – Data Structures
Linked List :: Basic Concepts
Data Structure Interview Question and Answers
12 C Data Structures.
Data Structures and Algorithms
Stacks and Queues.
Stack and Queue APURBO DATTA.
Queues Chapter 4.
Stack and Queue.
CMSC 341 Lecture 5 Stacks, Queues
Review & Lab assignments
Data Structures and Algorithms
Programming and Data Structure
BY PROF. IRSHAD AHMAD LONE.
Presentation transcript:

Data Structures

Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions that operate on the ADT

Data Structure Consist of the data structure definition and a collection of functions that operate on the struct –We will never access the struct directly!

Separate what you can do with data from how it is represented Other parts of the program interacts with data through provided operations according to their specifications Implementation chooses how to represent data and implement its operations

Multiple Implementations An ADT can have several implementations Interface functions are the same Application programs will not see any difference

ADT: Linear list A sequence of elements There is first and last element Each element has previous and next –Nothing before first –Nothing after last

Why linked lists ? A linked list is a dynamic data structure. –It can grow or shrink in size during the execution of a program. –It can be made just as long as required. –It does not waste memory space. Linked lists provide flexibility in allowing the items to be rearranged efficiently. –Insert an element. –Delete an element.

What we can do with a linear list? –Delete element –Insert element –Find element –Traverse list

Illustration: Insertion Item to be inserted X AB ABC C X

Illustration: Deletion CAB ABC

In essence... For insertion: –A record is created holding the new item. –The next pointer of the new record is set to link it to the item which is to follow it in the list. –The next pointer of the item which is to precede it must be modified to point to the new item. For deletion: –The next pointer of the item immediately preceding the one to be deleted is altered, and made to point to the item following the deleted item.

Traverse: list  elements in order get_first(list) - –returns first element if it exists get_next(list) - –returns next element if it exists Both functions return NULL otherwise Calling get_next in a loop we will get one by one all elements of the list

How we can implement a list? Array? Search is easy (sequential or binary) Traversal is easy: for(i = first; i <= last; ++i) process(a[i]); Insert and delete is not easy –a good part of the array has to be moved! Hard to guess the size of an array

A linked list implementation Linked list is a chain of elements Each element has data part and link part pointing to the next element

Main operations Create list Add node –beginning,middle or end Delete node –beginning,middle or end Find node Traverse list

Conceptual Idea List implementation and the related functions Insert Delete Traverse

Example: Working with linked list Consider the structure of a node as follows: struct stud { int roll; char name[25]; int age; struct stud *next; }; /* A user-defined data type called “node” */ typedef struct stud node; node *head;

Creating a List To start with, we have to create a node (the first node), and make head point to it. head = (node *) malloc (sizeof (node)); head next age name roll

Contd. If there are n number of nodes in the initial linked list: –Allocate n records, one by one. –Read in the fields of the records. –Modify the links of the records so that the chain is formed.

void create_list (node *list) { int k, n; node *p; printf (“\n How many elements?”); scanf (“%d”, &n); list = (node *) malloc (sizeof (node)); p = list; for (k=0; k<n; k++) { scanf (“%d %s %d”, &p->roll, p->name, &p->age); p->next = (node *) malloc (sizeof (node)); p = p->next; } free (p->next); p->next = NULL; } To be called from the main() function as: node *head; ……. create_list (head);

Traversing the List Once the linked list has been constructed and head points to the first node of the list, –Follow the pointers. –Display the contents of the nodes as they are traversed. –Stop when the next pointer points to NULL.

void display_list (node *list) { int k = 0; node *p; p = list; while (p != NULL) { printf (“Node %d: %d %s %d”, k, p->roll, p->name, p->age); k++; p = p->next; }

Inserting a Node in the List The problem is to insert a node before a specified node. –Specified means some value is given for the node (called key). –Here it may be roll. Convention followed: –If the value of roll is given as negative, the node will be inserted at the end of the list.

When a node is added at the beginning, –Only one next pointer needs to be modified. head is made to point to the new node. New node points to the previously first element. When a node is added at the end, –Two next pointers need to be modified. Last node now points to the new node. New node points to NULL. When a node is added in the middle, –Two next pointers need to be modified. Previous node now points to the new node. New node points to the next node.

void insert_node (node *list) { int k = 0, rno; node *p, *q, *new; new = (node *) malloc (sizeof (node)); scanf (“%d %s %d”, &new->roll, new->name, &new->age); printf (“\nInsert before roll (-ve for end):”); scanf (“%d”, &rno); p = list; if (p->roll == rno) /* At the beginning */ { new->next = p; list = new; }

while ((p != NULL) && (p->roll != rno)) { q = p; p = p->next; } if (p == NULL) /* At the end */ { q->next = new; new->next = NULL; } if (p->roll == rno) /* In the middle */ { q->next = new; new->next = p; } The pointers q and p always point to consecutive nodes.

Deleting an Item Here also we are required to delete a specified node. –Say, the node whose roll field is given. Here also three conditions arise: –Deleting the first node. –Deleting the last node. –Deleting an intermediate node.

void delete_node (node *list) { int rno; node *p, *q; printf (“\nDelete for roll :”); scanf (“%d”, &rno); p = list; if (p->roll == rno) /* Delete the first element */ { list = p->next; free (p); }

while ((p != NULL) && (p->roll != rno)) { q = p; p = p->next; } if (p == NULL) /* Element not found */ printf (“\nNo match :: deletion failed”); if (p->roll == rno) /* Delete any other element */ { q->next = p->next; free (p); }

Doubly linked list ABC Assignment : Insertion, deletion in a doubly linked list

A First-in First-out (FIFO) List Also called a QUEUE In Out ACB AB

A Last-in First-out (LIFO) List In Out ABCCB Also called a STACK

Stack

Stacks in Our Life

More Stacks A stack is a LIFO structure: Last In First Out

Basic Operations with Stacks Push –Add and item Overflow Pop –Remove an item Underflow Stack Top –What’s on the Top Could be empty

Push Adds new data element to the top of the stack

Removes a data element from the top of the stack Pop

Checks the top element. Stack is not changed Stack Top

STACK push create pop isfull isempty

Assume:: stack contains integer elements void push (stack s, int element); /* Insert an element in the stack */ int pop (stack s); /* Remove and return the top element */ void create (stack s); /* Create a new stack */ int isempty (stack s); /* Check if stack is empty */ int isfull (stack s); /* Check if stack is full */

We shall look into two different implementations of stack: –Using arrays –Using linked list

Stack Implementation

Stack Implementation Using Arrays Basic idea. –Declare an array of fixed size (which determines the maximum size of the stack). –Keep a variable which always points to the “top” of the stack.

Declaration #define MAXSIZE 100 struct lifo { int st[MAXSIZE]; int top; }; typedef struct lifo stack;

Stack Creation void create (stack s) { s.top = 0; /* Points to last element pushed in */ }

Pushing an element into the stack void push (stack s, int element) { if (s.top == (MAXSIZE-1)) { printf (“\n Stack overflow”); break; } else { s.top ++; s.st [s.top] = element; }

Removing/Popping an element from the stack int pop (stack s) { if (s.top == 0) { printf (“\n Stack underflow”); break; } else { return (s.st [s.top --]); }

Checking for stack full / empty int isempty (stack s) { if (s.top == 0) return 1; else return (0); } int isfull (stack s) { if (s.top == (MAXSIZE – 1)) return 1; else return (0); }

Stack Implementation Using Linked List Very similar to the linked list implementation discussed earlier. struct lifo { int element; struct lifo *next; }; typedef struct lifo stack; stack *top;

Contd. Basic concept: –Insertion (push) and deletion (pop) operations take place at one end of the list only. –For stack creation / push operation Required to call malloc function –How to check stack underflow? Easy. Simply check if top points to NULL. –How to check overflow? Check is malloc returns –1.

Sample Usage stack A, B; create (A); create (B); push (A, 10); push (A, 20); push (A, 30); push (B, 5); push (B, 25); push (B, 10); printf (“\n%d %d %d”, pop(A), pop(A), pop(A)); printf (“\n%d %d %d”, pop(B), pop(B), pop(B)); if (not isfull (A)) push (A, 50); if (not isempty (A)) k = pop (A);

Queues

A queue is a FIFO structure: Fast In First Out Queues in Our Life

Basic Operations with Queues Enqueue - Add an item to the end of queue Overflow Dequeue - Remove an item from the front Could be empty Queue Front - Who is first? Could be empty Queue End - Who is last? Could be empty

Enqueue

Dequeue

Queue Front

Queue Rear

Queue implementation with arrays

Queue will overgrow the array Should we use VERY L A R G E ARRAYS?

Array implementation of queues queueArymaxsizecountfrontrear frontrear 7415

Structure for a queue array struct intqueue { int *queueArray; int maxSize; int count; int front; int rear; };

Queue Implementation Using Linked List Basic idea: –Create a linked list to which items would be added to one end and deleted from the other end. –Two pointers will be maintained: One pointing to the beginning of the list (point from where elements will be deleted). Another pointing to the end of the list (point where new elements will be inserted). Front Rear

Assume:: queue contains integer elements void enqueue (queue q, int element); /* Insert an element in the queue */ int dequeue (queue q); /* Remove an element from the queue */ queue *create (); /* Create a new queue */ int isempty (queue q); /* Check if queue is empty */ int size (queue q); /* Return the number of elements in queue */

Creating a queue front = NULL; rear = NULL;

Inserting an element in queue void enqueue (queue q, int x) { queue *ptr; ptr = (queue *) malloc (sizeof (queue)); if (rear == NULL) /* Queue is empty */ { front = ptr; rear = ptr; ptr->element = x; ptr->next = NULL; } else /* Queue is not empty */ { rear->next = ptr; ptr ->element = x; ptr->next = NULL; }

Deleting an element from queue int dequeue (queue q) { queue *old; if (front == NULL) /* Queue is empty */ printf (“\n Queue is empty”); else if (front == rear) /* Single element */ { k = front->element; free (front); front = rear = NULL; return (k); } else { k = front->element; old = front; front = front->next; free (old); return (k); }

Checking if empty int isempty (queue q) { if (front == NULL) return (1); else return (0); }