Doubly linked list recursion

Lecture 12 Doubly Linked Lists (with Recursion)

Advertisement


Advertisement
Similar documents
Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

10CS35: Data Structures Using C

DATA STRUCTURES USING C

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Node-Based Structures Linked Lists: Implementation

Data Structures Using C++ 2E. Chapter 5 Linked Lists

LINKED DATA STRUCTURES

Lecture Notes on Binary Search Trees

Analysis of a Search Algorithm

Sequential Data Structures

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

PES Institute of Technology-BSC QUESTION BANK

ADTs,, Arrays, Linked Lists

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Data Structures Using C++ 2E. Chapter 5 Linked Lists

- Easy to insert & delete in O(1) time - Don t need to estimate total memory needed. - Hard to search in less than O(n) time

Lecture Notes on Binary Search Trees

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Unordered Linked Lists

recursion, O(n), linked lists 6/14

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

TREE BASIC TERMINOLOGIES

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Lecture 11 Array of Linked Lists

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Stacks. Linear data structures

Symbol Tables. Introduction

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Common Data Structures

Algorithms and Data Structures Exercise for the Final Exam (17 June 2014) Stack, Queue, Lists, Trees, Heap

Data Structure [Question Bank]

Data Structures and Algorithms Lists

Binary Search Trees CMPSC 122

Data Structure with C

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Data Structures Fibonacci Heaps, Amortized Analysis

System Software Prof. Dr. H. Mössenböck

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Ordered Lists and Binary Trees

The ADT Binary Search Tree

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,

Section IV.1: Recursive Algorithms and Recursion Trees

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT. Course Curriculum. DATA STRUCTURES (Code: )

Data Structures. Level 6 C Module Descriptor

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

Introduction to data structures

Universidad Carlos III de Madrid

Introduction to Object-Oriented Programming

Algorithms and Data Structures

Chapter 8: Bags and Sets

root node level: internal node edge leaf node Data Structures & Algorithms McQuain

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Data Structures and Algorithms

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

CSE 211: Data Structures Lecture Notes VII

Data Structures and Data Manipulation

Dynamic Programming Problem Set Partial Solution CMPSC 465

Persistent Binary Search Trees

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Module 2 Stacks and Queues: Abstract Data Types

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Linked Lists Linked Lists, Queues, and Stacks

Stack & Queue. Darshan Institute of Engineering & Technology. Explain Array in detail. Row major matrix No of Columns = m = u2 b2 + 1

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara

Data Structures, Practice Homework 3, with Solutions (not to be handed in)

Queues. Manolis Koubarakis. Data Structures and Programming Techniques

Binary Heap Algorithms

Lecture 11: Tail Recursion; Continuations

Dynamic Programming. Lecture Overview Introduction

Project 4 DB A Simple database program

Data Structures and Algorithms

Singly linked lists (continued...)

Sample Questions Csci 1112 A. Bellaachia

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

Review of Hashing: Integer Keys

Converting a Number from Decimal to Binary

Record Storage and Primary File Organization

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

arrays C Programming Language - Arrays

CS 2412 Data Structures. Chapter 2 Stacks and recursion

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

Introduction to Data Structures

Introduction to Data Structures and Algorithms

Data storage Tree indexes

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

A binary search tree is a binary tree with a special property called the BST-property, which is given as follows:

Cost Model: Work, Span and Parallelism. 1 The RAM model for sequential computation:

Advertisement
Transcription:

Lecture 12 Doubly Linked Lists (with Recursion) In this lecture Introduction to Doubly linked lists What is recursion? Designing a node of a DLL Recursion and Linked Lists o Finding a node in a LL (recursively) o Printing a LL (recursively) o Appending a node to a LL (recursively) o Reversing a LL (recursively) Further Readings Exercises Introduction to Doubly Linked Lists As we learnt before, singly linked list is a structure that contains at least two fields, data field and a pointer to the next node. Singly linked lists are flexible structures where memory can be allocated in small blocks as needed. Also, when deleting or inserting nodes from a singly linked list, the overhead is relatively low compared to array insertions where array elements have to be moved with a greater cost. This makes singly linked lists (LL) preferred data structures to use in many applications. However, one drawback in LL is that list can only be navigated in one direction and all navigations must start from the head node. But imagine an application where nodes needs to be inserted quickly, in order, and the data file typically provides clusters of data that needs to be inserted close to each other. It is quite common in data sets to have related data close to each other. For example, think of a user database where names are almost sorted and therefore needs to be inserted next to each other. In this case, it makes sense for the current pointer to remain in place until the next value is read from the data set. Based on the value of the date set, the current pointer can move forward or backwards to insert data in correct place. A doubly linked list is a collection of objects linked together by references from one object to another object, both forward and backward. By convention these objects are named as nodes. So the basic DLL is a collection of nodes where each node contains one or more data fields AND references to next node and previous node. The next pointer of the last node points to a NULL reference and the previous pointer of first node points to NULL to indicate the end of the list in both ways.

data data data The entry point into a DLL is always the first or head of the list. It should be noted that head is NOT a separate node, but a reference to the first Node in the list. If the list is empty, then the head has the value NULL. Unlike Arrays, nodes cannot be accessed by an index since memory allocated for each individual node may not be contiguous. We must begin from the head of the list and traverse the list sequentially to access the nodes in the list. Insertions of new nodes and deletion of existing nodes are fairly easy to handle. Recall that array insertions or deletions may require adjustment of the array (overhead), but insertions and deletions in linked lists can be performed very efficiently. Designing a Doubly Linked List Node A doubly linked list node contains, minimally a data field and two pointers, one to next node and other to previous node. The following struct can be used to define a DLL node typedef struct DLLNode { void* data; struct DLLNode *next; struct DLLNode* prev; DLLNode; Introduction to Recursion Recursion is the process of an object to refer to another object that may have the same structure. Recall that the definition of node in a singly linked list is called a recursive data structure. That is, the definition of the node includes a reference to itself. This allows us to create a linked list, where each node points to another node just like that. Therefore, linked lists are ideal data structures for implementing recursive algorithms. Recursive algorithms are elegant and allow us to solve complex problems that are otherwise may be difficult to solve. Another benefit of recursion is that the solution to the problem is constructed using a solution to a simple case, and a solution to a recursive problem. Recursion is fairly close to mathematical induction where a theorem is proved by first verifying a simple case, and then showing that the theorem holds for the value n+1, assuming that the theorem holds for some value n, Therefore in recursive algorithms being able to enumerate the problem is critical. Linked lists are ideal structures for recursive algorithms as one can think of nodes can be enumerated from 1 to n (or 0 to n- 1).

Recursion and Linked Lists Let us begin with a simple definition of a recursive search in a LL. Suppose we are looking for a node in a list. Then either the search node is the first one on the list or node must be on a smaller list (that is a list that contains all nodes but the first node, we typically call this the tail of the list). We can express this fact more mathematically as follows: found if target = first of LL search(ll, target) = not found if LL = NULL search(tail(ll), target) otherwise Note few things about this definition. The solution to the problem is described simply using what we call a base case. Then the solution to a more general case is described. That is, the solution to searching a list with n nodes is described using solution to the problem of searching a list with n-1 nodes. Base Case Any recursive algorithm must have a base case. This is typically the simplest case, such as what is the solution if n = 0 or n =1 or list is empty etc. The base case plays a major role in ending a sequence of recursive calls. Note that in the above example of search we have two outcomes, either the target is found when target is the first node or target is not found, if the list is NULL. Recursive Case This is the case where solution to a larger problem is described using a solution to a smaller case. For example, we ask the question, if we know the solution to n-1 th problem, can we find the solution to the n th problem (or vice versa). Note in the above case, we state that if first node is not the target, then we can reduce the search space by 1, by searching the tail of the LL. This guarantees that we will eventually find the node or we will reach the case, where our search list has only one node or none. Implementation Once we have the correct recursive definition, then implementation is straight forward. We simply convert the definition into a function as follows. (We assume that our node is a node that contains string as its data field. We should change the function header as necessary for the given node type) int searchrecurse(node* head, string target) { if (head == NULL) return 1; /* search fail. Target not found */ else if (strcmp(head data,target) == 0) return 0; /* search success. Target found */ else return searchrecurse(head next, target);

Tracing the Recursive Algorithm Suppose we need to trace this algorithm to see how this might work. Consider the following list of nodes. For simplicity we have only shown names and links. andy guna hill ian zoo NULL Suppose we are looking for the target zoo. Here is how we trace the recursive code. Note that the bold faced first argument represent the whole LL. searchrecurse(andy, zoo ) searchrecurse(guna, zoo ) searchrecurse(hill, zoo ) searchrecurse(ian, zoo ) searchrecurse(zoo, zoo ) 0 (success) We note that the final call searchrecurse(zoo, zoo ) result in a success since first node of the list zoo is the same as the target zoo. Exercise: Draw the trace of the call searchrecurse(andy, billy ). In this case you must return 1 for failure. Cost of Recursion Although recursion seems elegant, and closer to how we think about solving a problem Mathematically, there is a significant cost to recursion. The cost of recursion is associated with the many calls that are made using the run time stack. As functions calls other functions, the run time stack tends to grow. If we are making many recursive calls, it is possible that recursion may affect the working memory and therefore may slow down the program or crash. Hence the decision to use of recursion must be carefully weigh against the available resources. If the available resources are minimal, you must avoid the recursion at all cost. Other Examples of Recursion Given below are more examples of recursion for some standard LL operations. We note that all these definitions apply to any type of LL, including DLL s. Example 2 Definition head = target InsertToEnd(LL, target) = inserttoend(tail(ll), target) If LL = NULL otherwise Implementation node inserttoend(node* head, node* target) { if (head == NULL) { head = target; return head; return inserttoend(head next, target);

Tracing inserttoend (andy, billy ) inserttoend (guna, billy ) inserttoend (hill, billy ) inserttoend (ian, billy ) inserttoend (zoo, billy ) Example 3 Reversing a LL using recursion requires a definition as follows. If the list is empty or has only one node, then return the same list (this is the base case). If the list contains more than one node, then we can define reverse as follows. LL reverse(ll) = inserttoend(reverse(tail(ll)), firstof(ll)) if LL = empty otherwise Implementation node* reverse(node* head) { if (head == NULL) { return head; else { return inserttoend(reverse(head next), head)) Example 4 The following code displays printing a LL recursively. int printll(node* head){ if (head == NULL) printf( NULL\n ); else { printf( %d, *(head data)); printll(head next);

Further Readings Exercises

2021 © DocPlayer.net Privacy Policy|Terms of Service|Feedback |Do Not Sell My Personal Information