Linked Lists. 2 Merge Sorted Lists Write an algorithm that merges two sorted linked lists The function should return a pointer to a single combined list.

Slides:



Advertisements
Similar presentations
1 - Recursion on linked lists Lecture 7 ADS2 Lecture 7.
Advertisements

Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Inserting a Node into a Specified Position of a Linked List To create a node for the new item newNode = new Node(item); To insert a node between two nodes.
Linked Lists Chapter 4.
Lists A list is a finite, ordered sequence of data items. Important concept: List elements have a position. Notation: What operations should we implement?
CS 367 – Introduction to Data Structures
Data Structures ADT List
Section 5 Lists again. Double linked lists – insertion, deletion. Trees.
Lecture 6 Sept 11, 2008 Goals for the day: Linked list and project # 1 list class in STL (section 3.3) stack – implementation and applications.
PRESENTED BY MATTHEW GRAF AND LEE MIROWITZ Linked Lists.
Section 2.5 Single-Linked Lists. A linked list is useful for inserting and removing at arbitrary locations The ArrayList is limited because its add and.
Linked List Variations
David Weinberg presents Linked Lists: The Background  Linked Lists are similar to ArrayLists in their appearance and method of manipulation  They do.
Building a Linked List in Java. Linked List In the Procedural Paradigm a linked list consisted of: –A pointer to the head of the list –Nodes (in dynamic.
1 Queues (5.2) CSE 2011 Winter May Announcements York Programming Contest Link also available from.
Variations on Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Data Structures: A Pseudocode Approach with C 1 Chapter 5 Contd... Objectives Explain the design, use, and operation of a linear list Implement a linear.
Linked Lists
Lecture 2 Aug goals: Introduction to recursion examples of recursive programs.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 17: Linked Lists.
Linked Lists. Example We would like to keep a list of inventory records – but only as many as we need An array is a fixed size Instead – use a linked.
Lecture 5 Sept 12, 2011 Goals: Linked list (Chapter 3) list class in STL (section 3.3) implementing with linked lists.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 17 Linked.
Searching Chapter 18 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
© 2004 Goodrich, Tamassia Linked Lists1. © 2004 Goodrich, Tamassia Linked Lists2 Singly Linked List (§ 4.4.1) A singly linked list is a concrete data.
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Stack and Queue.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Analyzing Complexity of Lists OperationSorted Array Sorted Linked List Unsorted Array Unsorted Linked List Search( L, x ) O(logn) O( n ) O( n ) Insert(
1 Chapter 3. Recursion Lecture 6. In functions and data structures.
CS162 - Topic #11 Lecture: Recursion –Problem solving with recursion –Work through examples to get used to the recursive process Programming Project –Any.
 2008 Pearson Education, Inc. All rights reserved. 1 Member data stores a value of type parameter NODETYPE Member nextPtr stores a pointer to the next.
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
CSE 341 Lecture 4 merge sort; basic efficiency issues Ullman slides created by Marty Stepp
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 17: Linked Lists.
Lists and Iterators Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented Programming.
M180: Data Structures & Algorithms in Java Linked Lists – Part 2 Arab Open University 1.
Recursive Objects (Part 2) 1. Adding to the front of the list  adding to the front of the list  t.addFirst('z') or t.add(0, 'z') 2 'a' 'x' LinkedList.
LINKED LIST’S EXAMPLES Salim Malakouti. Linked List? 523 Pointer Node ValuePointer.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Java linked list.
1 CSC 211 Data Structures Lecture 11 Dr. Iftikhar Azim Niaz 1.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Lists List Implementations. 2 Linked List Review Recall from CMSC 201 –“A linked list is a linear collection of self- referential structures, called nodes,
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
Given a node v of a doubly linked list, we can easily insert a new node z immediately after v. Specifically, let w the be node following v. We execute.
Recursion repetition without loops. Recursion  definition solving a problem in terms of a smaller version of itself  form of a recursive solution: base.
CSE 143 Lecture 9: introduction to recursion reading: 12.1.
CS1020 L AB 3 (L INKED L IST ) Problem 1: Balls Problem 2: Josephine Problem 3: Keyboard.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Lectures linked lists Chapter 6 of textbook
Linked lists Motivation: we can make arrays, but their functionality is slightly limited and can be difficult to work with Biggest issue: size management.
Chapter 4 Linked Lists
Notes on Assignment 1 Your code will have several classes, most notably the class that represents the entire list data structure, and the class.
Merge Sort Merge sort is a recursive algorithm for sorting that decomposes the large problem.
Chapter 4 Linked Lists.
Data Structures ADT List
Data Structures ADT List
Programming Linked Lists.
[Chapter 4; Chapter 6, pp ] CSC 143 Linked Lists [Chapter 4; Chapter 6, pp ]
Chapter 17: Linked Lists Starting Out with C++ Early Objects
Recursive Linked List Operations
Chapter 4 Linked Lists.
Linked List and Selection Sort
Data Structures ADT List
List Iterator Implementation
Generic Set Algorithms
Presentation transcript:

Linked Lists

2 Merge Sorted Lists Write an algorithm that merges two sorted linked lists The function should return a pointer to a single combined list The two input lists can be destroyed The output list should not contain any duplicate values Unnecessary nodes should be freed

3 Merge Sorted Lists – Iterative Solution Concept Traverse lists L1 and L2 using two pointers, and compare elements If the element from L1 is smaller – move to the next one If the element from L2 is smaller – insert it into L1 (before the compared L1 element)

4 Merge Sorted Lists – Iterative Solution MERGE-LISTS (L1, L2) // Simple case – point head to first node of L1. if (L1.val <= L2.val) head  L1 else // Special case - first node in L2 is smaller. head  L2 // Smallest value is first. temp  L2.next // Save pointer to next. L2.next  L1 // The rest of L1 follows. L2  temp // Point to next node in L2. prev  head // Save for future insertions.

5 Merge Sorted Lists – Iterative Solution (continued) // Traverse both lists, insert L2 nodes into L1. while (L1 != null && L2 != null) if (L1.val < L2.val) if (L1.next = null) L1.next  L2 // Append remainder of L2. L1  null // Exit loop. else prev  L1 // Save pointer to previous. L1  L1.next // Move to next node.

6 Merge Sorted Lists – Iterative Solution (continued) else if (L1.val > L2.val) temp  L2.next // Save pointer to next. L2.next  L1 // Insert L2 node before L1. prev.next  L2 L2  temp // Point to next node in L2. else // (L1.val = L2.val) temp  L2 // Save pointer for freeing. L2  L2.next // Duplicate – skip it. free (temp) return head

7 Merge Sorted Lists – Recursive Solution MERGE-LISTS (L1, L2) switch case L1 = null: head  L2 case L2 = null: head  L1 case L1.val < L2.val: head  L1 head.next  MERGE-LISTS (L1.next, L2) case L1.val > L2.val: head  L2 head.next  MERGE-LISTS (L1, L2.next) case L1.val = L2.val: head  L1 head.next  MERGE-LISTS (L1.next, L2.next) free (L2) return head

8 Merge Unsorted Lists What if the lists are not sorted? If we also want to remove duplicates, must compare each element in one list, with all elements in the other Complexity: O(n 2 ) If we give up on this requirement, can we do better?

9 Merge Unsorted Lists Yes: simply append the lists APPEND-LIST (L1, L2) if (L1 = null) L1  L2 else cur  L1 while (cur.next != null) cur  cur.next cur.next  L2

10 Reverse Linked List Write a function that accepts a linked list as input, and reverses it in place No nodes should be freed or created – only the pointers should be changed We will start by writing an iterative solution, and then give a recursive one

11 Iterative Reverse ITERATIVE_REVERSE (list) result  null cur  list while (cur != null) next  cur.next cur.next  result result  cur cur  next list  result

12 Iterative Reverse – Java Implementation public void iterativeReverse() { ListNode result = null, cur = head, next; while (cur != null) { next = cur.getNext(); cur.setNext (result); result = cur; cur = next; } head = result; }

13 Recursive Reverse The straightforward solution: Save the first element Reverse the rest of the list Append the first element and make it last This will work, but instead of O(n) for the iterative solution, will take O(n 2 ) Is there an O(n) recursive solution?

14 Recursive Reverse – O(n 2 ) RECURSIVE_REVERSE (list) if (list = null) return null first  list rest  list.next if (rest = null) return list rest  RECURSIVE_REVERSE (rest) cur  rest while (cur.next != null) cur  cur.next cur.next  first first.next  null return rest

15 Recursive Reverse – O(n) RECURSIVE_REVERSE (list) if (list = null) return null first  list rest  list.next if (rest = null) return list rest  RECURSIVE_REVERSE (rest) first.next.next  first first.next  null return rest

16 Recursive Reverse – Java Implementation When writing pseudocode, a list is simply a pointer to the first element The type of the list is "pointer to list node" In Java, the list is wrapped by a class, which contains a head pointer as a field The list has a type of its own Only the head field itself is of type "pointer to list node"

17 Recursive Reverse – Java Implementation The recursive call needs to get a pointer to the list head as a parameter, but this pointer is a private field Therefore, a wrapper method should be provided to expose the functionality: public void reverse() { head = reverseRec (head); }

18 Recursive Reverse – Java Implementation private static ListNode reverseRec (ListNode list) { ListNode first, rest; if (list == null) return null; first = list; rest = list.getNext(); if (rest == null) return list; rest = reverseRec (rest); first.getNext().setNext (first); first.setNext (null); return rest; }