Laboratorio di Algoritmi e Strutture Dati

Size: px
Start display at page:

Download "Laboratorio di Algoritmi e Strutture Dati"

Transcription

1 Laboratorio di Algoritmi e Strutture Dati Guido Fiorino guido.fiorino@unimib.it aa

2 2 Linked lists (of int) We focus on linked lists for integers; let us start with a class that defines a node of the list: class Node{ int data; Node next; we want to define the class LinkedList to store arbitrary long sequences of integers by means of a linked list. The definition of the class LinkedList has the following features: 1 the class Node will be an inner class of LinkedList; 2 head will be an instance variable of type Node. As usual, head equals null means empty list, otherwise head points to the first node of the list. Notice that for practical purposes, LinkedList could have more instance variables, such as one to point to the last node, one containing the number of items,...

3 The class LinkedList This is the skeleton of the class LinkedList. In the next slides we develop some methods for the class. public class LinkedList{ private class Node{ int data; Node next; //end Node private Node head; /* methods go here, see next slides */ //end LinkedList

4 The class LinkedList: constructors public LinkedList(){ //creates an empty list head = null; // end constructor // creates a list with a node public LinkedList(int x){ head = new Node(); head.data = x; head.next = null; // end constructor

5 The class LinkedList: check for emptiness public boolean isempty(){ //returns true if the list is empty, //false otherwise return head == null; // end isempty()

6 The class LinkedList: head insert and delete //add a node to the head of the list public void insertasfirst(int x){ Node n = new Node(); n.data = x; n.next = head; head = n; // end insertasfirst //remove the first node public boolean deletefirst(){ if (head == null) return false; //nothing to delete head = head.next; return true;

7 The class LinkedList: check for the existence public boolean exists(int x){ // returns true if x occurs as a data in a node of the list, // false otherwise return exists(head, x); //call a private recursive method private boolean exists(node p, int x){ if ( p == null ) return false; return (p.data == x) ( exists(p.next, x) ) ;

8 The class LinkedList: traversing the list to multiply The method multiplyby(int x) multiplies by x the instance variable data of every node. The method void multiplyby(int x) calls method void multiplyby(node p, int x) that by recursion traverses the list starting from p. public void multiplyby(int x){ multiplyby(head, x); // end multiplyby(int) private void multiplyby(node p, int x){ if (p!= null){ p.data *= x; multiplyby(p.next, x); // end multiplyby(node, int)

9 The class LinkedList: traversing the list to print public void print(){ if ( head!= null ){ System.out.println("Data in the list"); print(head); else System.out.println("The list is empty"); // end print() private void print(node p){ if (p!= null){ System.out.println("data: " + p.data); print(p.next); // end print(node)

10 The class LinkedList: tail insertion The method void insertaslast(int x) creates a new node and insert it as the last node of the list. public void insertaslast(int x){ if (head == null) insertasfirst(x); //the list is empty else insertaslast(head,x); private void insertaslast(node p, int x){ if (p.next==null) { //base case //p is pointing to the last node Node g = new Node(); g.data= x; g.next = null; p.next=g; /* In alternative we can save g: p.next = new Node(); p.next.data = x; p.next.next = null; */ return; // end if insertaslast(p.next, x);//recursione

11 The class LinkedList: tail deletion We devise a pubic method deletelast that returns true if the list is not empty, false is the list is empty and thus there is nothing to delete. The easy part is for the empty list or the list with one element. For the list with more than one element, the public method deletelast() calls the private method deletelast(node p). public boolean deletelast(){ if (head == null) return false; // nothing to delete; if (head.next == null){ // the list has one element head = null; return true; // the list has two or more elements return deletelast(head);

12 The class LinkedList: tail deletion private boolean deletelast(node p){ // base case Node front = p.next; //front points to the successor of p if ( front.next == null){ //if the successor of p is the last element //then p becomes the last element p.next = null; return true; return deletelast(front);

13 The class LinkedList: deletion of all nodes with a value The method deletedata(int x) deletes all the nodes containing the given value x. The easy part is when the list is empty; If the first node has to be deleted, we proceed recursively on the (public) method deletedata(int x). For the other cases we proceed recursively by means of the (private) method deletedata(node p, int x). //delete all the nodes containing the value x public boolean deletedata(int x){ if (head == null) return false; // the list is empty, // nothing to do if (head.data == x) { //the first node has to be deleted head = head.next; deletedata(x); return true; //the first node must not be deleted return deletedata(head,x); // end deletedata(int)

14 The class LinkedList: deletion of all nodes with a value private boolean deletedata(node p, int x){ //p points a node that does not contain x Node front = p.next; // front points to the successor of p, if any if (front == null) return false; //p has no successor if (front.data == x) { // delete the successor of p p.next = front.next; //now p.next different from front deletedata(p, x); return true; //the successor of p must not by deleted //recursively proceed on the rest of the list return deletedata(front, x); // deletedata(node, int)

15 The class LinkedList: print in reverse public void printreverse(){ if ( head!= null ){ System.out.println("Data of the list"); printreverse(head); else System.out.println("The list is empty"); // end printreverse() private void printreverse(node p){ if (p!= null){ printreverse(p.next); System.out.println("data: " + p.data); // end printreverse(node)

16 The class LinkedList: reverse the list Build the reverse of the given list by reversing the pointers; when we finish, head points to the last node of the original given list; no new node is created, only the value of next is changed; public void reverse(){ if (head!= null && head.next!= null) //there is more than one element head=reverse(head);

17 The class LinkedList: reverse the list private Node reverse(node p){ if (p.next == null) return p; //there is one element //there is more than one element: //recursively reverse the list starting from the successor of p Node r = reverse(p.next); /* now the list starting from the node successor of p is reversed and r points to it. The first node of the given list pointed by p must become the last node of the list pointed by r. We change the pointer of the the successor of p, which is the last node of the list pointed by r. */ p.next.next=p; //now the successor of p points to p p.next=null; //the given list is fully reversed return r;

18 The class LinkedList: copy the data We want a method copy that returns an object of LinkedList; the instance variable head points to a list whose data are equal to the original list; note that by copy we mean a genuine duplicate of the data in the given object. //duplicates the nodes of the list pointed by head public LinkedList copy(){ LinkedList thecopy = new LinkedList(); thecopy.head = copy(head); //duplicate the list return thecopy; private Node copy(node p){ Node g; if (p == null) return null; //the given list is empty; g = new Node(); g.data = p.data; g.next = copy(p.next); //recursively copy the rest of the list return g;

19 19 A collection of exercises on the class LinkedList Provide and iterative version of the recursive methods given in the previous slides; write a method int size() that returns the number of nodes in the list; write a method int getat(int k) that returns the value stored in the k-th node of the list (k = 1 means the first node). If the list has less than k nodes, then getat() returns the value of the last node. You are free to handle the cases of the empty list or of k < 1. write a method boolean insertat(int x, int k) that creates a new node and assigns x to the instance variable data. If the list has less than k 1 nodes, the method insertat() places the new node as last node and returns false. Otherwise, the method insertat() places the new node in the k-th position and returns true; write a method boolean deleteat(int k) that removes the node at the k-th position and returns true if the k-th node of the list exists, false otherwise; write a method int lastpositionof(int x) that returns the last position where x occurs, -1 if x does not occur in the list; write a method void moveahead(int x) that if the value x does not occur in the list, then creates a new node and inserts it as first node of the list. Otherwise moveahead makes one of the nodes containing x the first node of the list; write a method LinkedList concatenate(linkedlist g) that returns an object of LinkedList containing the data pointed by head followed by the data contained in g.

20 20 Circular linked lists A circular linked list is a linked list where the link of the last node references the head node of the list. Consequences: every node has a predecessor and a successor; given a reference to any node, we can traverse the whole list. We follow the definition of the class LinkedList to define the class CircularLinkedList. In particular: CircularLinkedList has one Node instance variable last. The methods handle last as the reference to the last node of the list.

21 The class CircularLinkedList public class CircularLinkedList{ private class Node{ int data; Node next; // end Node private Node last; // last.next points to the head list public CircularLinkedList(){ //creates an empty list last = null; // end constructor // creates a list with a node public CircularLinkedList(int x){ last = new Node(); last.data = x; last.next = last; // this is both the first and // the last node of the list // end constructor /* methods go here, see next slides */ // end class

22 The class CircularLinkedList: handling the first element public int getfirst(){ // returns the value in the first node of // the list. Note that // if last == null holds we get an error return last.next.data; public void deletefirst(){ if (last == null) return; // the list is empty if (last.next!= last){ //there are at least 2 elements last.next = last.next.next; else { // the list has one element last = null;

23 The class CircularLinkedList: check for the existence public boolean exists(int x){ // returns true if x occurs as a data in a node of the list, // false otherwise if (last == null) return false; //the list is empty return exists(last.next, x); //search from the head node private boolean exists(node p, int x){ if ( p == last ) return (last.data == x); return ( p.data == x ) ( exists(p.next, x) ) ;

24 The class CircularLinkedList: traversing the list to print public void print(){ if ( last!= null ){ //the list is not empty System.out.println("Data in the list"); print(last.next); else System.out.println("The list is empty"); // end print() private void print(node p){ System.out.println("data: " + p.data); if (p!= last){ print(p.next); // end print(node)

25 The class CircularLinkedList: head insertion public void insertasfirst(int x){ if (last == null){ //the list is empty last = new Node(); last.data=x; last.next=last; else { // the list is not empty Node n = new Node(); n.data = x; n.next = last.next; // the successor of n is the first node last.next = n; // the successor of the last node is n // end insertasfirst(int)

26 The class CircularLinkedList: tail insertion public void insertaslast(int x){ if (last == null) insertasfirst(x); else { // the list is not empty Node n = new Node(); n.data = x; n.next = last.next; //the successor of n is the first node last.next = n; // the predecessor of n is pointed by last last = n; // makes the new node the last element // end insertaslast(int)

27 A collection of exercises for the class CircularLinkedList Add to the class the methods given for the class LinkedList; write a method int size() that returns the number of nodes in the list; write a method int getat(int k) that returns the value stored in the k-th node of the list (k = 1 means the first node). If the list has less than k nodes, then getat() returns the value of the last node. You are free to handle the cases of the empty list or of k < 1. Remember that the first node is the successor of the node referenced by the instance variable last. write a method boolean insertat(int x, int k) that creates a new node and assigns x to the instance variable data. If the list has less than k 1 nodes, insertat() places the new node as last node and returns false. Otherwise, insertat() places the new node in the k-th position and returns true; write a method boolean deleteat(int k) that removes the node at the k-th position and returns true if the k-th node of the list exists, false otherwise; write a method int lastpositionof(int x) that returns the last position where x occurs, -1 if x does not occur in the list; write a method void moveahead(int x) that if the value x does not occur in the list, then creates a new node and inserts it as first node of the list. Otherwise, moveahead() makes one of the nodes containing x the first node of the list; write a method CircularLinkedList concatenate(circularlinkedlist g) that returns an object of CircularLinkedList containing the data pointed by head followed by the data contained in g.

28 28 (Circular) doubly linked lists In a (circular) doubly linked list there is no a privileged direction to traverse the list because every node brings information to access both to the predecessor and to the successor: every node has two instances variables to reference the nodes. We call them next and prev; the instance variable next references the successor; the instance variable prev references the predecessor. Analogously to linked lists, double linked lists have: a node without a predecessor, where prev is null. We call it the first node or the head node of the list; a node without a successor, where next is null. We call it the last node or the tail node of the list. Analogously to circular linked lists, all the nodes of a circular doubly linked list have a predecessor.

29 The class DoublyLinkedList public class DoublyLinkedList{ private class Node{ int data; Node next; Node prev; // end Node private Node head; private Node tail; // not necessary but useful /* methods go here, see the next slides //end class

30 The class DoublyLinkedList: the constructors public DoublyLinkedList(){ head = tail = null; // creates an empty list // end constructor // creates a list with a node public DoublyLinkedList(int x){ head = new Node(); tail = head ; // in a one-node list the node is both // the head and the tail head.data = x; head.next = null; //the node has no successor head.prev = null; //the node has no predecessor // end constructor

31 The class DoublyLinkedList: insertion public void insertasfirst(int x){ Node n = new Node(); n.data = x; n.next = head; n.prev = null; // the first node has no predecessor if (head!= null){ // the list is not empty, // also tail!= null holds // only head needs to be updated head.prev = n; head = n; else { // the list is empty this is //the first node and also tail == null holds // head and tail need to be updated head = tail = n; // end insertasfirst(int)

32 The class DoublyLinkedList: insertion public void insertaslast(int x){ Node n = new Node(); n.data = x; n.next = null; //n is the last node n.prev = tail; //the predecessor of n is //the last node of the list if (tail!= null){ //the list is not empty tail.next = n; //n becomes the successor of the last node tail = n; //n becomes the last node of the list else head = tail = n; // end insertaslast(int)

33 The class CircularDoublyLinkedList public class CircularDoublyLinkedList{ private class Node{ int data; Node next; prev; // end Node private Node last; // points to the last node of the list // last.next is the first node of the list /*methods go here, see next slides*/ // end class

34 The class CircularDoublyLinkedList: the constructors public CircularDoublyLinkedList(){ last = null; // creates an empty list // end constructor // creates a list with a node public CircularDoublyLinkedList(int x){ last = new Node(); last.data = x; last.next = last.prev = last; // the node has itself // as predecessor and successor // end constructor / end class

35 35 Exercises for the classes of double linked lists Complete the classes DoublyLinkedList and CircularDoublyLinkedList with the methods given for the class LinkedList. Pay attention to the insertion and deletion methods for the class CircularDoublyLinkedList!

36 36 Implementation of FIFO queue via linked lists By using the class CircularLinkedList introduced before it is easy to implement a class Queue that handles collection of integers according the policy first-in-first-out. The class Queue contains the following methods: void enqueue(int) to add an integer; int dequeue() to remove the last recently added item; boolean isempty() to check if the queue is empty.

37 The class Queue for integers //a fifo queue implemented by means of a circular linked list public class Queue{ private CircularLinkedList queueofint = new CircularLinkedList(); public boolean isempty(){ return queueofint.isempty(); public void enqueue(int data){ //insert as last element of the queue queueofint.insertaslast(data); public int dequeue(){ //delete the first item of the queue int data=queueofint.getfirst(); queueofint.deletefirst(); return data;

38 38 Implementation of Pushdown stack via circular linked lists By using the class LinkedList introduced before it is easy to implement a class Stack that handles collection of integers according the policy last-in-first-out. The class Stack contains the following methods: void push(int) to add an integer; int pop() to remove the last recently added item; boolean isempty() to check if the queue is empty.

39 The class Stack for integers public class Stack{ private LinkedList stackofint = new LinkedList(); public boolean isempty(){ return stackofint.isempty(); public void push(int data){ // add data to the top of the stack stackofint.insertasfirst(data); public int pop(){ // remove the data from the top of the stack int data = stackofint.getat(1); stackofint.deletefirst(); return data;

40 40 Exercises Write a class to handle stack of characters. Then use the class to: write a method boolean balanced(string s) that returns true if the parenthesis in s are balanced. For example balanced( [()({){] ) should return true and balanced( {[([])] ) should return false; write a method int evaluate(string s) that returns the value of the arithmetic expression contained in s. Suppose that the expression is fully parenthesized, the unary minus is not used and the numbers have one digit.

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today Introduction to Linked Lists Stacks and Queues using Linked Lists Next Time Iterative Algorithms on Linked Lists Reading:

More information

Linked Structures. See Section 3.2 of the text.

Linked Structures. See Section 3.2 of the text. Linked Structures See Section 3.2 of the text. First, notice that Java allows classes to be recursive, in the sense that a class can have an element which is itself an object of that class: class Person

More information

COL106: Data Structures and Algorithms. Ragesh Jaiswal, IIT Delhi

COL106: Data Structures and Algorithms. Ragesh Jaiswal, IIT Delhi Stack and Queue How do we implement a Queue using Array? : A collection of nodes with linear ordering defined on them. Each node holds an element and points to the next node in the order. The first node

More information

16. Dynamic Data Structures

16. Dynamic Data Structures Data Structures 6. Dynamic Data Structures A data structure is a particular way of organizing data in a computer so that it can be used efficiently Linked lists, Abstract data types stack, queue, Sorted

More information

CS171 Midterm Exam. October 29, Name:

CS171 Midterm Exam. October 29, Name: CS171 Midterm Exam October 29, 2012 Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 50 minutes to complete this exam. Read each problem carefully, and

More information

DNHI Homework 3 Solutions List, Stacs and Queues

DNHI Homework 3 Solutions List, Stacs and Queues Solutions List, Stacs and Queues Problem 1 Given the IntegerQueue ADT below state the return value and show the content of the, initially empty, queue of Integer objects after each of the following operations.

More information

Linked List Nodes (reminder)

Linked List Nodes (reminder) Outline linked lists reminders: nodes, implementation, invariants circular linked list doubly-linked lists iterators the Java foreach statement iterator implementation the ListIterator interface Linked

More information

Data Structures and Algorithms. Chapter 5. Dynamic Data Structures and Abstract Data Types

Data Structures and Algorithms. Chapter 5. Dynamic Data Structures and Abstract Data Types 1 Data Structures and Algorithms Chapter 5 and Abstract Data Types Werner Nutt 2 Acknowledgments The course follows the book Introduction to Algorithms, by Cormen, Leiserson, Rivest and Stein, MIT Press

More information

8. Fundamental Data Structures

8. Fundamental Data Structures 172 8. Fundamental Data Structures Abstract data types stack, queue, implementation variants for linked lists, [Ottman/Widmayer, Kap. 1.5.1-1.5.2, Cormen et al, Kap. 10.1.-10.2] Abstract Data Types 173

More information

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013 Linear Structure Linear Structures Chapter 4 CPTR 318 Every non-empty linear structure has A unique element called first A unique element called last Every element except last has a unique successor Every

More information

[2:3] Linked Lists, Stacks, Queues

[2:3] Linked Lists, Stacks, Queues [2:3] Linked Lists, Stacks, Queues Helpful Knowledge CS308 Abstract data structures vs concrete data types CS250 Memory management (stack) Pointers CS230 Modular Arithmetic !!!!! There s a lot of slides,

More information

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10 Keeping Order:! Stacks, Queues, & Deques 1 Stacks 2 Stacks A stack is a last in, first out (LIFO) data structure Primary Operations: push() add item to top pop() return the top item and remove it peek()

More information

Introduction to Computer Science II CS S-20 Linked Lists III

Introduction to Computer Science II CS S-20 Linked Lists III Introduction to Computer Science II CS112-2012S-20 Linked Lists III David Galles Department of Computer Science University of San Francisco 20-0: Linked List Previous Practical Example: removeat(int index)

More information

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Readings List Implementations Chapter 20.2 Objectives Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Additional references:

More information

Linked Lists. Linked List Nodes. Walls and Mirrors Chapter 5 10/25/12. A linked list is a collection of Nodes: item next -3.

Linked Lists. Linked List Nodes. Walls and Mirrors Chapter 5 10/25/12. A linked list is a collection of Nodes: item next -3. Linked Lists Walls and Mirrors Chapter 5 Linked List Nodes public class Node { private int item; private Node next; public Node(int item) { this(item,null); public Node(int item, Node next) { setitem(item);

More information

Queues Fall 2018 Margaret Reid-Miller

Queues Fall 2018 Margaret Reid-Miller Queues 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Writing methods various classes that implement Lists. Methods using Lists and Big-O w/ ArrayList or LinkedLists Prove

More information

CIS Fall Data Structures Midterm exam 10/16/2012

CIS Fall Data Structures Midterm exam 10/16/2012 CIS 2168 2012 Fall Data Structures Midterm exam 10/16/2012 Name: Problem 1 (30 points) 1. Suppose we have an array implementation of the stack class, with ten items in the stack stored at data[0] through

More information

CS350: Data Structures Linked Lists

CS350: Data Structures Linked Lists Linked Lists James Moscola Department of Physical Sciences York College of Pennsylvania James Moscola Linked Lists Come in a variety of different forms - singly linked lists - doubly linked lists - circular

More information

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013 Linear Structure Linear Structures Chapter 4 CPTR 318 Every non-empty linear structure has A unique element called first A unique element called last Every element except last has a unique successor Every

More information

1. Introduction. Lecture Content

1. Introduction. Lecture Content Lecture 6 Queues 1 Lecture Content 1. Introduction 2. Queue Implementation Using Array 3. Queue Implementation Using Singly Linked List 4. Priority Queue 5. Applications of Queue 2 1. Introduction A queue

More information

Abstract Data Types. Abstract Data Types

Abstract Data Types. Abstract Data Types Abstract Data Types Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria Wolfgang.Schreiner@risc.jku.at http://www.risc.jku.at Wolfgang Schreiner

More information

DS L9: Queues

DS L9: Queues Indian Institute of Science Bangalore, India भ रत य व ज ञ न स स थ न ब गल र, भ रत Department of Computational and Data Sciences DS286 2016-09-09 L9: Queues Yogesh Simmhan s i m m h a n @ c d s. i i s c.

More information

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue Queues CSE 2011 Fall 2009 9/28/2009 7:56 AM 1 Queues: FIFO Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue Applications,

More information

Dynamic Data Structures

Dynamic Data Structures Dynamic Data Structures We have seen that the STL containers vector, deque, list, set and map can grow and shrink dynamically. We now examine how some of these containers can be implemented in C++. To

More information

1.00 Introduction to Computers and Engineering Problem Solving. Final Examination - May 19, 2004

1.00 Introduction to Computers and Engineering Problem Solving. Final Examination - May 19, 2004 1.00 Introduction to Computers and Engineering Problem Solving Final Examination - May 19, 2004 Name: E-mail Address: TA: Section: You have 3 hours to complete this exam. For coding questions, you do not

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms First Semester 2017/2018 Linked Lists Eng. Anis Nazer Linked List ADT Is a list of nodes Each node has: data (can be any thing, int, char, Person, Point, day,...) link to

More information

Assignment 1. Check your mailbox on Thursday! Grade and feedback published by tomorrow.

Assignment 1. Check your mailbox on Thursday! Grade and feedback published by tomorrow. Assignment 1 Check your mailbox on Thursday! Grade and feedback published by tomorrow. COMP250: Queues, deques, and doubly-linked lists Lecture 20 Jérôme Waldispühl School of Computer Science McGill University

More information

1. Stack Implementation Using 1D Array

1. Stack Implementation Using 1D Array Lecture 5 Stacks 1 Lecture Content 1. Stack Implementation Using 1D Array 2. Stack Implementation Using Singly Linked List 3. Applications of Stack 3.1 Infix and Postfix Arithmetic Expressions 3.2 Evaluate

More information

CMSC 132: Object-Oriented Programming II. Stack and Queue

CMSC 132: Object-Oriented Programming II. Stack and Queue CMSC 132: Object-Oriented Programming II Stack and Queue 1 Stack Allows access to only the last item inserted. An item is inserted or removed from the stack from one end called the top of the stack. This

More information

(6-1) Basics of a Queue. Instructor - Andrew S. O Fallon CptS 122 (September 26, 2018) Washington State University

(6-1) Basics of a Queue. Instructor - Andrew S. O Fallon CptS 122 (September 26, 2018) Washington State University (6-1) Basics of a Queue Instructor - Andrew S. O Fallon CptS 122 (September 26, 2018) Washington State University What is a Queue? 2 A linear data structure with a finite sequence of nodes, where nodes

More information

Tutorial 2: Linked Lists

Tutorial 2: Linked Lists Tutorial 2: Linked Lists ? 2 Agenda Introduction of Linked List Arrays Vs Linked Lists Types of Linked Lists Singly Linked List Doubly Linked List Circular Linked List Operations Insertion Deletion 3 Data

More information

csci 210: Data Structures Stacks and Queues

csci 210: Data Structures Stacks and Queues csci 210: Data Structures Stacks and Queues 1 Summary Topics Stacks and Queues as abstract data types ( ADT) Implementations arrays linked lists Analysis and comparison Applications: searching with stacks

More information

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011 Stacks (5.1) CSE 2011 Winter 2011 26 January 2011 1 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data Error

More information

Lecture 3 Linked List

Lecture 3 Linked List Lecture 3 Linked List Bo Tang @ SUSTech, Spring 2018 Our Roadmap Linked List Definition Linked List Operators Illustration Example 2 Representing a Sequence of Data An ordered collection of items (position

More information

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR STUDENT IDENTIFICATION NO MULTIMEDIA COLLEGE JALAN GURNEY KIRI 54100 KUALA LUMPUR FIFTH SEMESTER FINAL EXAMINATION, 2014/2015 SESSION PSD2023 ALGORITHM & DATA STRUCTURE DSEW-E-F-2/13 25 MAY 2015 9.00 AM

More information

Computer Science 136 Exam 2

Computer Science 136 Exam 2 Computer Science 136 Exam 2 Sample exam Show all work. No credit will be given if necessary steps are not shown or for illegible answers. Partial credit for partial answers. Be clear and concise. Write

More information

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014 Lists CSC212 Lecture 8 D. Thiebaut, Fall 2014 Review List = Organization of Data in a Linear Fashion, where Order is Important Set of actions that can be carried out efficiently on the data. Typical Actions

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

Queues. Lesson 4. CS 32: Data Structures Dept. of Computer Science

Queues. Lesson 4. CS 32: Data Structures Dept. of Computer Science Queues Lesson 4 Outline What is a queue? Straight queue Circular Queue Sequential Implementation Linked Implementation Application: Topological sort Deques Final Notes Outline What is a queue? Straight

More information

Lecture Notes CPSC 122 (Fall 2014) Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S.

Lecture Notes CPSC 122 (Fall 2014) Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S. Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S. Bowers 1 of 11 Doubly Linked Lists Each node has both a next and a prev pointer head \ v1 v2 v3 \ tail struct

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 11 Introduction to Computing II Wayne Snyder Department Boston University Today Object-Oriented Programming Concluded Stacks, Queues, and Priority Queues as Abstract Data Types Reference types: Basic

More information

Linked Lists. Chapter 4

Linked Lists. Chapter 4 Linked Lists Chapter 4 1 Linked List : Definition Linked List: A collection of data items of the same type that are stored in separate objects referred to as "nodes". Each node contains, in addition to

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018 CSC 172 Data Structures and Algorithms Lecture #9 Spring 2018 SINGLY LINKED LIST 3.1.3 Linked lists We will consider these for Singly linked lists Doubly linked lists Basic Singly Linked List class Node

More information

Introduction to Computer Science II CS S-18 Linked Lists

Introduction to Computer Science II CS S-18 Linked Lists Introduction to Computer Science II CS112-2012S-18 Linked Lists David Galles Department of Computer Science University of San Francisco 18-0: Linked Lists Linked List node Data Pointer to the next element

More information

CMSC 341 Lecture 7 Lists

CMSC 341 Lecture 7 Lists CMSC 341 Lecture 7 Lists Today s Topics Linked Lists vs Arrays Nodes Using Linked Lists Supporting Actors (member variables) Overview Creation Traversal Deletion UMBC CMSC 341 Lists 2 Linked Lists vs Arrays

More information

Introduction. Reference

Introduction. Reference Introduction Data Structures - Linked Lists 01 Dr TGI Fernando 1 2 Problems with arrays Unordered array - searching is slow, deletion is slow Ordered array - insertion is slow, deletion is slow Arrays

More information

CSE 143 SAMPLE MIDTERM SOLUTION

CSE 143 SAMPLE MIDTERM SOLUTION CSE 143 SAMPLE MIDTERM SOLUTION 1. (5 points) In some methods, you wrote code to check if a certain precondition was held. If the precondition did not hold, then you threw an exception. This leads to robust

More information

Name CPTR246 Spring '17 (100 total points) Exam 3

Name CPTR246 Spring '17 (100 total points) Exam 3 Name CPTR246 Spring '17 (100 total points) Exam 3 1. Linked Lists Consider the following linked list of integers (sorted from lowest to highest) and the changes described. Make the necessary changes in

More information

Linked List. April 2, 2007 Programming and Data Structure 1

Linked List. April 2, 2007 Programming and Data Structure 1 Linked List April 2, 2007 Programming and Data Structure 1 Introduction head A linked list is a data structure which can change during execution. Successive elements are connected by pointers. Last element

More information

An Introduction to Trees

An Introduction to Trees An Introduction to Trees Alice E. Fischer Spring 2017 Alice E. Fischer An Introduction to Trees... 1/34 Spring 2017 1 / 34 Outline 1 Trees the Abstraction Definitions 2 Expression Trees 3 Binary Search

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 07: Linked Lists MOUNA KACEM mouna@cs.wisc.edu Spring 2019 Linked Lists 2 Introduction Linked List Abstract Data Type SinglyLinkedList ArrayList Keep in Mind Introduction:

More information

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11. Lecture 11 1 More Data Structures In this lecture we will use a linked list to implement two abstract data types (ADT) An ADT provides the interface, or what a data structure does We can then use code

More information

CPSC 260 Data Structures and Algorithms for Computer Engineers Linked Lists!

CPSC 260 Data Structures and Algorithms for Computer Engineers Linked Lists! CPSC 260 Data Structures and Algorithms for Computer Engineers Linked Lists! Winter 2013 Instructor: Hassan Khosravi Problems with Arrays and Vectors With arrays and vectors you are allocated a large space.

More information

Introduction to Computer Science I

Introduction to Computer Science I Introduction to Computer Science I P 6.0: Data Structures Dr. Thomas Kühne, Juniorprofessor FG Metamodeling TU Darmstadt Data Structures Agenda why abstract datatypes? implementation of and use of some

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

Fun facts about recursion

Fun facts about recursion Outline examples of recursion principles of recursion review: recursive linked list methods binary search more examples of recursion problem solving using recursion 1 Fun facts about recursion every loop

More information

CS 216 Exam 1 Fall SOLUTION

CS 216 Exam 1 Fall SOLUTION CS 216 Exam 1 Fall 2004 - SOLUTION Name: Lab Section: Email Address: Student ID # This exam is closed note, closed book. You will have an hour and fifty minutes total to complete the exam. You may NOT

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists Prof. amr Goneid, AUC 1 Linked Lists Prof. amr Goneid, AUC 2 Linked Lists The Linked List Structure Some Linked List

More information

CSC212:Data Structure

CSC212:Data Structure CSC212:Data Structure 1 Queue: First In First Out (FIFO). Used in operating systems, simulations etc. Priority Queues: Highest priority item is served first. Used in operating systems, printer servers

More information

Linked Lists. Chapter 12.3 in Savitch

Linked Lists. Chapter 12.3 in Savitch Linked Lists Chapter 12.3 in Savitch Preliminaries n Arrays are not always the optimal data structure: q An array has fixed size needs to be copied to expand its capacity q Adding in the middle of an array

More information

CS6202 - PROGRAMMING & DATA STRUCTURES I Unit IV Part - A 1. Define Stack. A stack is an ordered list in which all insertions and deletions are made at one end, called the top. It is an abstract data type

More information

Stacks Fall 2018 Margaret Reid-Miller

Stacks Fall 2018 Margaret Reid-Miller Stacks 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Today: Quiz 5 solutions Recursive add from last week (see SinglyLinkedListR.java) Stacks ADT (Queues on Thursday) ArrayStack

More information

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage: Discussion 2C Notes (Week 3, January 21) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Abstraction In Homework 1, you were asked to build a class called Bag. Let

More information

CSE 230 Intermediate Programming in C and C++

CSE 230 Intermediate Programming in C and C++ CSE 230 Intermediate Programming in C and C++ Structures and List Processing Fall 2017 Stony Brook University Instructor: Shebuti Rayana http://www3.cs.stonybrook.edu/~cse230/ Self-referential Structure

More information

UNIT-1. Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays.

UNIT-1. Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays. UNIT-1 Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays. Chapter 2 (Linked lists) 1. Definition 2. Single linked list 3.

More information

More Data Structures (Part 1) Stacks

More Data Structures (Part 1) Stacks More Data Structures (Part 1) Stacks 1 Stack examples of stacks 2 Top of Stack top of the stack 3 Stack Operations classically, stacks only support two operations 1. push 2. pop add to the top of the stack

More information

CS24 Week 4 Lecture 2

CS24 Week 4 Lecture 2 CS24 Week 4 Lecture 2 Kyle Dewey Overview Linked Lists Stacks Queues Linked Lists Linked Lists Idea: have each chunk (called a node) keep track of both a list element and another chunk Need to keep track

More information

Extra Credit: write mystrlen1 as a single function without the second parameter int mystrlen2(char* str)

Extra Credit: write mystrlen1 as a single function without the second parameter int mystrlen2(char* str) CPSC 122 Study Guide 3: Final Examination The final examination will consist of three parts: Part 1 covers mostly C++. For this, see study guides 1 and 2, exams 1 and 2, and part of exam 3, and quizzes

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in themodel answer scheme. 2) The model answer and the answer written by candidate may

More information

Abstract Data Types 1

Abstract Data Types 1 Abstract Data Types 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues 2 Abstract Data Types (ADTs) ADT is a set of objects together with a set of operations. Abstract in that implementation of operations

More information

1 Deletion in singly linked lists (cont d) 1 Other Functions. 1 Doubly Linked Lists. 1 Circular lists. 1 Linked lists vs. arrays

1 Deletion in singly linked lists (cont d) 1 Other Functions. 1 Doubly Linked Lists. 1 Circular lists. 1 Linked lists vs. arrays Unit 3: Linked Lists Part 2: More on Linked Lists 1 Deletion in singly linked lists (cont d) 1 Other Functions Engineering 4892: Data Structures 1 Doubly Linked Lists Faculty of Engineering & Applied Science

More information

Programming. Lists, Stacks, Queues

Programming. Lists, Stacks, Queues Programming Lists, Stacks, Queues Summary Linked lists Create and insert elements Iterate over all elements of the list Remove elements Doubly Linked Lists Circular Linked Lists Stacks Operations and implementation

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Stacks Eng. Anis Nazer First Semester 2017-2018 Stack An Abstract data type (ADT) Accessed only on one end Similar to a stack of dishes you can add/remove on top of stack

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

References and Homework ABSTRACT DATA TYPES; LISTS & TREES. Abstract Data Type (ADT) 9/24/14. ADT example: Set (bunch of different values)

References and Homework ABSTRACT DATA TYPES; LISTS & TREES. Abstract Data Type (ADT) 9/24/14. ADT example: Set (bunch of different values) 9// References and Homework Text: Chapters, and ABSTRACT DATA TYPES; LISTS & TREES Homework: Learn these List methods, from http://docs.oracle.com/javase/7/docs/api/java/util/list.html add, addall, contains,

More information

Introduction to Data Structures and Algorithms

Introduction to Data Structures and Algorithms Introduction to Data Structures and Algorithms Data Structure is a way of collecting and organising data in such a way that we can perform operations on these data in an effective way. Data Structures

More information

(Divide and Conquer) Electrical & Computer Engineering University of Waterloo Canada. February 14, Divide And Conquer

(Divide and Conquer) Electrical & Computer Engineering University of Waterloo Canada. February 14, Divide And Conquer ( ) Electrical & Computer Engineering University of Waterloo Canada February 14, 2007 Divide And BinarySearch is an (arguably degenerate) instance of a basic algorithm design pattern: Divide And 1. If

More information

Advanced Linked Lists. Doubly Linked Lists Circular Linked Lists Multi- Linked Lists

Advanced Linked Lists. Doubly Linked Lists Circular Linked Lists Multi- Linked Lists Advanced Linked Lists Doubly Linked Lists Circular Linked Lists Multi- Linked Lists Review The singly linked list: consists of nodes linked in a single direction. access and traversals begin with the first

More information

CS S-20 Linked Lists III 1. We can then use the next pointer of the previous node to do removal (example on board)

CS S-20 Linked Lists III 1. We can then use the next pointer of the previous node to do removal (example on board) CS112-2012S-20 Linked Lists III 1 20-0: Linked List ious Practical Example: removeat(int index) remove( o) 20-1: removeat First need to get to node before the one we want to remove We can then use the

More information

Mid-Term- ECE 242 Fall 2016 Closed book/notes- no calculator- no phone- no computer

Mid-Term- ECE 242 Fall 2016 Closed book/notes- no calculator- no phone- no computer Mid-Term- ECE 242 Fall 2016 Closed book/notes- no calculator- no phone- no computer NAME: ID: Problem 1- General questions (14pts) 2- Big-O (18pts) 3- Sorting (25pts) 4- Queue (8pts) 5- Stack (8pts) 6-

More information

Topic 6: Inner Classes

Topic 6: Inner Classes Topic 6: Inner Classes What's an inner class? A class defined inside another class Three kinds: inner classes static nested classes anonymous classes this lecture: Java mechanisms later: motivation & typical

More information

infix expressions (review)

infix expressions (review) Outline infix, prefix, and postfix expressions queues queue interface queue applications queue implementation: array queue queue implementation: linked queue application of queues and stacks: data structure

More information

Linked List. ape hen dog cat fox. tail. head. count 5

Linked List. ape hen dog cat fox. tail. head. count 5 Linked Lists Linked List L tail head count 5 ape hen dog cat fox Collection of nodes with a linear ordering Has pointers to the beginning and end nodes Each node points to the next node Final node points

More information

CSE 373 Data Structures and Algorithms. Lecture 2: Queues

CSE 373 Data Structures and Algorithms. Lecture 2: Queues CSE 373 Data Structures and Algorithms Lecture 2: Queues Queue ADT queue: A list with the restriction that insertions are done at one end and deletions are done at the other First-In, First-Out ("FIFO

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 07: Linked Lists and Iterators MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Linked Lists 2 Introduction Linked List Abstract Data Type General Implementation of the ListADT

More information

Data Structures and Algorithms. Roberto Sebastiani

Data Structures and Algorithms. Roberto Sebastiani Data Structures and Algorithms Roberto Sebastiani roberto.sebastiani@disi.unitn.it http://www.disi.unitn.it/~rseba - Week 05 - B.S. In Applied Computer Science Free University of Bozen/Bolzano academic

More information

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3 UNIT 3 LINEAR DATA STRUCTURES 1. Define Data Structures Data Structures is defined as the way of organizing all data items that consider not only the elements stored but also stores the relationship between

More information

CMSC 341. Linked Lists. Textbook Section 3.5

CMSC 341. Linked Lists. Textbook Section 3.5 CMSC 341 Linked Lists Textbook Section 3.5 1 Implementing A Linked List To create a doubly linked list as seen below MyLinkedList class Node class LinkedListIterator class Sentinel nodes at head and tail

More information

Data Structures. Alice E. Fischer. Lecture 4, Fall Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall / 19

Data Structures. Alice E. Fischer. Lecture 4, Fall Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall / 19 Data Structures Alice E. Fischer Lecture 4, Fall 2018 Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall 2018 1 / 19 Outline 1 Ordered Lists 2 Sorted Lists Tail Pointers 3 Doubly Linked Lists

More information

CMSC 341. Linked Lists, Stacks and Queues. CMSC 341 Lists, Stacks &Queues 1

CMSC 341. Linked Lists, Stacks and Queues. CMSC 341 Lists, Stacks &Queues 1 CMSC 341 Linked Lists, Stacks and Queues CMSC 341 Lists, Stacks &Queues 1 Goal of the Lecture To complete iterator implementation for ArrayList Briefly talk about implementing a LinkedList Introduce special

More information

Stack and Queue. Stack:

Stack and Queue. Stack: Stack and Queue Stack: Abstract Data Type A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations

More information

Abstract Data Types. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Abstract Data Types. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University Abstract Data Types CptS 223 Advanced Data Structures Larry Holder School of Electrical Engineering and Computer Science Washington State University 1 Purpose Abstract Data Types (ADTs) Lists Stacks Queues

More information

List ADT. B/W Confirming Pages

List ADT. B/W Confirming Pages wu3399_ch8.qxd //7 :37 Page 98 8 List ADT O b j e c t i v e s After you have read and studied this chapter, you should be able to Describe the key features of the List ADT. the List ADT using an array

More information

University of Palestine. Final Exam 2 nd semester 2014/2015 Total Grade: 50

University of Palestine. Final Exam 2 nd semester 2014/2015 Total Grade: 50 First Question Q1 B1 Choose the best Answer: No. of Branches (1) (10/50) 1) 2) 3) 4) Suppose we start with an empty stack and then perform the following operations: Push (A); Push (B); Pop; Push (C); Top;

More information

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures MIDTERM EXAMINATION Spring 2010 CS301- Data Structures Question No: 1 Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the

More information

CSE 143 SAMPLE MIDTERM

CSE 143 SAMPLE MIDTERM CSE 143 SAMPLE MIDTERM 1. (5 points) In some methods, you wrote code to check if a certain precondition was held. If the precondition did not hold, then you threw an exception. This leads to robust code

More information

Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists.

Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists. Announcements MODULE WEB-SITE: http://www.csc.liv.ac.uk/ michele/teaching/comp102/comp102.html FIRST ASSIGNMENT DEADLINE: Wednesday, February 1st, 14.30, LAB 7 Boxes (late submissions to be left in the

More information

Data Structures. Outline. Introduction Linked Lists Stacks Queues Trees Deitel & Associates, Inc. All rights reserved.

Data Structures. Outline. Introduction Linked Lists Stacks Queues Trees Deitel & Associates, Inc. All rights reserved. Data Structures Outline Introduction Linked Lists Stacks Queues Trees Introduction dynamic data structures - grow and shrink during execution Linked lists - insertions and removals made anywhere Stacks

More information