241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective –...

69
241-423 ADSA: Linked Lists/5 241-423 Advanced Data Structures and Algorithms Objective implement and use linked lists Semester 2, 2013-2014 5. Linked Lists

Transcript of 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective –...

Page 1: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 1

241-423 Advanced Data Structures and Algorithms

• Objective– implement and use linked lists

Semester 2, 2013-2014

5. Linked Lists

Page 2: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 2

Contents1. An ArrayList can be Slow

2. What is a Linked List?

3. Java Assignment Differences

4. Implementing a Linked List

5. Using a Linked List

6. Doubly Linked Lists

7. The (Doubly) LinkedList Collection

8. Palindromes

Page 3: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 3

1. An ArrayList can be Slow• Inserting/removing an element inside an Inserting/removing an element inside an

ArrayList requires data shiftingArrayList requires data shifting– O(n) operationsO(n) operations

Page 4: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 4

• Each element (node) inside a linked list is Each element (node) inside a linked list is linked to the previous node and successor linked to the previous node and successor (next) node.(next) node.

• This allows for more efficient insertion and This allows for more efficient insertion and deletion of nodes. deletion of nodes. Why?Why?

2. What is a Linked List?

5 3 14 2

continued

Page 5: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 5

• Inserting a new node only involves breaking one link, Inserting a new node only involves breaking one link, and linking the list to both ends of the new node:and linking the list to both ends of the new node:– all are O(1) operationsall are O(1) operations

continued

Page 6: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 6

• Removal of a node only requires the breaking Removal of a node only requires the breaking of its two links, removal of the node, and then of its two links, removal of the node, and then the relinking of the list:the relinking of the list:– all are O(1) operationsall are O(1) operations

continued

Page 7: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 7

• The insertion/removal of a node is a The insertion/removal of a node is a local local operationoperation– only the links next to the node need to be changedonly the links next to the node need to be changed– the other nodes in the list are not affectedthe other nodes in the list are not affected– fast: O(1) fast: O(1)

• An ArrayList must shift lots of elements An ArrayList must shift lots of elements when an element is inserted/removedwhen an element is inserted/removed– slow: O(n) slow: O(n)

Page 8: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 8

3. Java Assignment Differences

32

Foo a = new Foo();Foo b;b = a;

int a = 32;int b;b = a;

b

32

a

ba

Foo object

copy the link (the reference)

copy the value

Page 9: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 9

4. Implementing a Linked List

• Each node is an object containing a value and Each node is an object containing a value and a link (reference) to the next node (object) in a link (reference) to the next node (object) in the listthe list– a singly-linked a singly-linked

listlist

• The list uses a 'front' variable to point to The list uses a 'front' variable to point to the first object in the list. the first object in the list.

• The reference in the last object is The reference in the last object is nullnull..

Page 10: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 10

• Nodes in a singly-linked list are accessed by Nodes in a singly-linked list are accessed by moving forward one node at a time from the moving forward one node at a time from the frontfront– called called sequential accesssequential access– a linked list is not a direct access structure like an a linked list is not a direct access structure like an

arrayarray– this means that access is slower than in an arraythis means that access is slower than in an array

• linked list access (if index is known): O(n)linked list access (if index is known): O(n)• array list access (if index is known): O(1)array list access (if index is known): O(1)

Accessing a Node

Page 11: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 11

Nodes in a Linked List

• Each Node object contains two variables:Each Node object contains two variables:– nodeValuenodeValue, of generic type T , of generic type T – nextnext, a reference that links to the next node , a reference that links to the next node

Page 12: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 12

The Node Classpublic class Node<T>{ public T nodeValue; // data held by the node public Node<T> next; // next node in the list

public Node() { nodeValue = null; next = null; }

public Node(T item) { nodeValue = item; next = null; }}

Page 13: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 13

• The variables in the Node class are public to The variables in the Node class are public to simplify the coding using linked listssimplify the coding using linked lists– bad style (from Ford & Topp, not me ☺)bad style (from Ford & Topp, not me ☺)

• The Node class is The Node class is self‑referencingself‑referencing: : – nextnext refers to (points to) an object of the same refers to (points to) an object of the same

typetype

Page 14: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 14

Creating a Linked List// create two nodes (figure (a)Node<String> p = new Node<String>("red");Node<String> q = new Node<String>("green")

// link p to qp.next = q; // figure (b)

// set front to point at the first nodeNode<String> front = p; // figure (c)

g re e nre d

(a ) C re a te n o d e s p a n d q

qp

g re e nre d

(c ) A s s ig n fro n t to p o in t a t p (re d )

qp

g re e nre d

(b ) Lin k p to q

qp

fro n t

continued

Page 15: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 15

• If the linked list is empty, front is assigned If the linked list is empty, front is assigned null.null.

Page 16: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 16

Scanning a Linked List

• We scan a singly linked list by starting at the front, and We scan a singly linked list by starting at the front, and then move along the list one Node at a timethen move along the list one Node at a time– sequential access (O(n))sequential access (O(n))

– stop when we reach nullstop when we reach null

• toString() is an example of a scanning method, which toString() is an example of a scanning method, which builds a string as it moves along the list.builds a string as it moves along the list.

Page 17: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 17

toString()public static <T> String toString(Node<T> front)// build a string from the list of the form // "[ n1, n2, ..., nx ]"{ if (front == null) // empty list return "[]";

Node<T> curr = front; // start at the front

String s = "[" + curr.nodeValue; while(curr.next != null) { curr = curr.next; // move along list s += ", " + curr.nodeValue; } s += "]"; return s;}

Page 18: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 18

Moving to a List Position

• To move to an element at position x, we To move to an element at position x, we need to start at the front and move through need to start at the front and move through the list counting up to xthe list counting up to x– sequential access again (O(n))sequential access again (O(n))

• The first element of the list is at position 0. The first element of the list is at position 0.

continued

Page 19: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 19

Node<T> curr = front; // start at the front of list

for (int i = 0; i < xPos; i++) curr = curr.next; // move along list

A s s ig n c u rr to fro n t

c u rr

fro n t

M o v e c u rr w ith 3 it e ra t io n s

fro n t

p o s 3

c u rr

p o s 0 p o s 2p o s 1p o s 3

Page 20: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 20

Updating the Front of the List

• Inserting or deleting an element at the front of Inserting or deleting an element at the front of a list is easy (and fast) because the 'front' a list is easy (and fast) because the 'front' variable always points to the first element:variable always points to the first element:– the operations are O(1)the operations are O(1)

Page 21: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 21

it e m

n e w N o d e

fro n t

/ /

Node<T> newNode = new Node<T>(item);

// insert item at the front of the listnewNode.next = front;front = newNode;

Insert at the Front

Page 22: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 22

fro n t

/ /

fro n t .n e xt

front = front.next; // move front to next node

Delete from the Front

Page 23: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 23

General Insertion

• To insert a new node before a node referenced To insert a new node before a node referenced by 'curr', the code must have access to the by 'curr', the code must have access to the previous node, 'prev', since its link must be previous node, 'prev', since its link must be changed.changed.

continued

Page 24: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 24

Node<T> curr = ... // set to point to a nodeNode<T> prev = ... // set to point to previous node

Node<T> newNode = new Node<T>(item); // new node

// update linksnewNode.next = curr; // step 1prev.next = newNode; // step 2

continued

Page 25: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 25

• The insertion is O(1) since only two links The insertion is O(1) since only two links need to be changed. But the real cost is the need to be changed. But the real cost is the sequential search to find the insertion sequential search to find the insertion position, which is O(n).position, which is O(n).

Page 26: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 26

General Deletion• Deleting a node at position curr requires Deleting a node at position curr requires

access to the predecessor node prev.access to the predecessor node prev.Node<T> curr = ... // set to point to a nodeNode<T> prev = ... // set to point to previous node

// connect prev to curr.nextprev.next = curr.next;curr.next = null;

continued

Page 27: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 27

• The deletion is O(1) since only two links The deletion is O(1) since only two links need to be changed. But the real cost is the need to be changed. But the real cost is the sequential search to find the deletion sequential search to find the deletion position, which is O(n)position, which is O(n)– this is shown in the remove() method, which is this is shown in the remove() method, which is

explained nextexplained next

Page 28: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 28

Removing a Target Node

• To remove the first node having a specified To remove the first node having a specified value, scan the list to find the node.value, scan the list to find the node.

• The scan must use two references that move The scan must use two references that move together down the list together down the list – one reference (curr) points to the current node in one reference (curr) points to the current node in

the scanthe scan– the other reference (prev) points to the previous the other reference (prev) points to the previous

nodenodecontinued

Page 29: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 29

• Once 'curr' finds the node, the code uses Once 'curr' finds the node, the code uses 'prev' to unlink 'curr'.'prev' to unlink 'curr'.

continued

Page 30: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 30

• At the start, point 'curr' at the front of the list and set At the start, point 'curr' at the front of the list and set 'prev' to null, since the first node does not have a 'prev' to null, since the first node does not have a predecessor.predecessor.

• Move 'curr' and 'prev' down the list until curr.nodeValue Move 'curr' and 'prev' down the list until curr.nodeValue matches the target ormatches the target orcurr == null.curr == null.

continued

Page 31: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 31

• If the target is found then 'curr' points at the If the target is found then 'curr' points at the node and 'prev' to the predecessor node.node and 'prev' to the predecessor node.

• But there are But there are twotwo possible cases: possible cases:– the target node is the first node, so 'prev' is nullthe target node is the first node, so 'prev' is null– the target node is the target node is notnot the first node, so 'prev' points the first node, so 'prev' points

to something to something

continued

Page 32: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 32

• Case 1Case 1:: 'prev' is null which means that 'curr' 'prev' is null which means that 'curr' points to the first node. points to the first node. – so we only have to delete the front of the listso we only have to delete the front of the list

front = curr.next;curr.next = null;

Page 33: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 33

• Case 2Case 2:: The match occurs in the middle of The match occurs in the middle of the list. Both 'curr' and 'prev' have non-null the list. Both 'curr' and 'prev' have non-null values. Unlink the current node. values. Unlink the current node.

prev.next = curr.next;curr.next = null;

continued

Page 34: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 34

• The generic remove() is passed a reference to The generic remove() is passed a reference to the front of the list and the target value.the front of the list and the target value.

• The method returns the value of 'front', which The method returns the value of 'front', which may have been updated if the first node was may have been updated if the first node was deleted.deleted.

Page 35: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 35

remove() Method

public static <T> Node<T> remove(Node<T> front, T target)/* Delete the first occurrence of the target in the linked list referenced by front; return the value of front */{ // initialize pointers Node<T> curr = front; Node<T> prev = null;

boolean foundItem = false; // set to true if we find the target :

Page 36: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 36

// scan until find item or end of list (O(n)) while (curr != null && !foundItem) { // check for a match if (target.equals(curr.nodeValue)) { if (prev == null) // remove first Node (O(1)) front = front.next; else // erase middle Node (O(1)) prev.next = curr.next; curr.next = null; foundItem = true; } else { // advance curr and prev prev = curr; curr = curr.next; } } return front; // may be updated} // end of remove()

Page 37: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 37

5. Using a Linked Listimport java.util.Random;import java.util.Scanner;

import ds.util.Node;import ds.util.Nodes; // methods using Node<T>

public class ListExample{ public static void main(String[] args) { // the initial list is empty Node<Integer> front = null;

Random rnd = new Random(); Scanner keyIn = new Scanner(System.in); :

Page 38: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 38

System.out.print("Enter the size of the list: "); int listCount = keyIn.nextInt();

// create a list Node<Integer> newNode; for (int i = 0; i < listCount; i++) { newNode = new Node<Integer>(rnd.nextInt(100)); newNode.next = front; // insert at list front front = newNode; }

System.out.print("Original list: "); System.out.println( Nodes.toString(front) ); :

Page 39: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 39

System.out.print("Ordered list: "); Node<Integer> p; while (front != null) { // list not empty p = getMaxNode(front); // get largest System.out.print(p.nodeValue + " "); front = Nodes.remove(front, p.nodeValue); } System.out.println(); } // end of main()

Page 40: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 40

public static <T extends Comparable<? super T>> Node<T> getMaxNode(Node<T> front) { Node<T> maxNode = front; // initial values Node<T> curr = front.next; T maxValue = front.nodeValue; while (curr != null) { // try to update maxNode and maxValue if (maxValue.compareTo(curr.nodeValue)< 0) { maxValue = curr.nodeValue; maxNode = curr; } curr = curr.next; } return maxNode; } // end of getMaxNode()

} // end of ListExample class

Page 41: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 41

Execution

Page 42: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 42

6. Doubly Linked Lists

• A node in a doubly-linked list contain two A node in a doubly-linked list contain two references that point to the next node references that point to the next node andand the the previous node.previous node.

• frontfront points to the first node in the listpoints to the first node in the list• backback points at the last node in the listpoints at the last node in the list

continued

Page 43: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 43

• A doubly-linked list can be scanned in both A doubly-linked list can be scanned in both directions:directions:– a forward scan starts at 'front' and ends when the a forward scan starts at 'front' and ends when the

link is to the same object as 'back'link is to the same object as 'back'– a backward scan starts at 'back' and ends when the a backward scan starts at 'back' and ends when the

link is to the same object as 'front'link is to the same object as 'front'

continued

Page 44: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 44

• Like a singly-linked list, a doubly linked list is a Like a singly-linked list, a doubly linked list is a sequential structure.sequential structure.

• To move forward or backward, use the node links To move forward or backward, use the node links 'next' and 'prev'.'next' and 'prev'.

• Unlike a singly linked list, the insert and delete Unlike a singly linked list, the insert and delete operations only need a single reference to the node. operations only need a single reference to the node.

continued

Page 45: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 45

• Insertion into a doubly linked list requires four Insertion into a doubly linked list requires four reference assignments.reference assignments.

prevNode = curr.prev;newNode.prev = prevNode; // 1prevNode.next = newNode; // 2curr.prev = newNode; // 3newNode.next = curr; // 4

continued

Page 46: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 46

• To delete a node curr, link the predecessor To delete a node curr, link the predecessor (curr.prev) of 'curr' to the successor of 'curr' (curr.prev) of 'curr' to the successor of 'curr' (curr.next).(curr.next).

prevNode = curr.prev;succNode = curr.next;succNode.prev = prevNode; // 1prevNode.next = succNode; // 2curr.prev = null;curr.next = null;

continued

Page 47: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 47

• In a singly-linked list, adding and removing a In a singly-linked list, adding and removing a node at the node at the frontfront of the list are O(1) operations. of the list are O(1) operations.

• With a doubly linked list, you can add and With a doubly linked list, you can add and remove a node at the remove a node at the backback of the list with the of the list with the same O(1) efficiency. same O(1) efficiency.

Page 48: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 48

7. The (Doubly) LinkedList Collection

In Ford & Topp's DSA package

Page 49: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 49

UML for LinkedList

Page 50: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 50

• The LinkedList() constructor creates an The LinkedList() constructor creates an empty list.empty list.

• The toString() method returns a string The toString() method returns a string representing the list as a comma-separated representing the list as a comma-separated sequence of elements enclosed in brackets. sequence of elements enclosed in brackets.

LinkedList Methods

continued

Page 51: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 51

• Reuse the Collection methods:Reuse the Collection methods:– isEmpty(), size(), contains(), toArray()isEmpty(), size(), contains(), toArray()

• add() inserts a new element at the back of the list and add() inserts a new element at the back of the list and returns true.returns true.

• remove() with an Object reference deletes the first remove() with an Object reference deletes the first occurrence of the object in the listoccurrence of the object in the list– the method returns true or false depending on whether a the method returns true or false depending on whether a

match was foundmatch was found

Page 52: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 52

LinkedList Examples

LinkedList<String> aList = new LinkedList<String>();alist.add("Red");alist.add("Green");alist.add("Blue);

System.out.println("Size = " + aList.size()); System.out.println("List contains the string 'White' is " +

aList.contains("White");

Size = 3List contains the string 'White' is false

Page 53: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 53

aList.add("Black"); // add Black at the endaList.add("Blue"); // add Blue at the end

aList.remove("Blue"); // delete first "Blue"

System.out.println(aList); // uses toString()

[Red, Green, Black, Blue]

Page 54: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 54

LinkedList Index Methods

• The LinkedList can access and update an The LinkedList can access and update an element with element with get()get() and and set()set(), and modify the , and modify the list with the list with the add()add() and and remove()remove()..

• The index methods have O(n) worst case The index methods have O(n) worst case running time. Use these methods only for running time. Use these methods only for small data sets.small data sets.

Page 55: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 55

Example

// create list containing [5,7,9,4,3]

Integer i= list.get(1); // i has value 7

list.remove(1); // remove value at position 1

continued

Page 56: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 56

list.set(2, 8); // store node 8 at position 2

list.add(2, 6); // store value 6 at position 2

Page 57: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 57

Accessing the Ends of a LinkedList

• Methods for the front of the list: Methods for the front of the list: – getFirst(), addFirst(), removeFirst()getFirst(), addFirst(), removeFirst()

• For the back of the list:For the back of the list:– getLast(), addLast(), removeLast()getLast(), addLast(), removeLast()

• They all are O(1) operationsThey all are O(1) operations

Page 58: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 58

End-of-List Examples

LinkedList<String> list = new LinkedList<String>();

list.addFirst("Tom");list.addFirst("Debbie");

list.addLast("David"); ist.addLast("Maria");

continued

Page 59: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 59

// identify the elements at the ends of the listSystem.out.println("First element is " + list.getFirst());System.out.println("Last element is " + list.getLast());

First element is DebbieLast element is Maria

continued

Page 60: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 60

// Exchange the first and last elements in the list.

// remove elements at the ends of the listString firstElem = aList.removeFirst();String lastElem = aList.removeLast();

// add elements back in switched positions aList.addLast(firstElem);aList.addFirst(lastElem);

continued

Page 61: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 61

// Output elements in the list by position.

// Repeatedly delete first element and display its // value until list is empty

while (!aList.isEmpty())System.out.print(aList.removeFirst() + " ");

Maria Tom David Debbie

Page 62: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 62

• A linked list is a natural way to implement a A linked list is a natural way to implement a queue. queue. – the element at the front of the queue can be the element at the front of the queue can be

removed with getFirst() removed with getFirst() – a new element can be added to the back of the a new element can be added to the back of the

queue by using addLast()queue by using addLast()

Linked List as a Queue

Page 63: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 63

8. Palindromes

• A palindrome is a string that reads A palindrome is a string that reads the same forward and backward:the same forward and backward:– e.g. "level", "noon.", "Stack Cats"e.g. "level", "noon.", "Stack Cats"– ignore non-letters and let capitals == lowercaseignore non-letters and let capitals == lowercase

• isPalindrome() takes a LinkedList object as an isPalindrome() takes a LinkedList object as an argument and returns true if the sequence is a argument and returns true if the sequence is a palindrome; false otherwise.palindrome; false otherwise.

continued

Page 64: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 64

Panic in a Titanic, I nap.

Race car

Yawn a more Roman way.

A Toyota's a Toyota

Page 65: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 65

public static boolean isPalindrome(LinkedList<?> aList){ // list must have 2 or more elements while (aList.size() > 1) { // compare elements on opposite ends of list if ( !aList.getFirst().equals(aList.getLast()) ) return false;

// delete the matching elements aList.removeFirst(); aList.removeLast(); }

// if we get here then list is a palindrome return true;}

Page 66: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 66

The "?" Wildcard

• isPalindrome() does not refer to the generic isPalindrome() does not refer to the generic type of the list. In this case, we may use:type of the list. In this case, we may use:

LinkedList<?> aListLinkedList<?> aList

• "?" means that we "?" means that we don't caredon't care about the type about the type of the elements of the list.of the elements of the list.

Page 67: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 67

Checking for a Palindromeimport java.util.Scanner;

import ds.util.LinkedList;

public class CheckPali{ public static void main(String[] args) { LinkedList<Character> charList = new LinkedList<Character>();

// get input line from user System.out.print("Enter a string: "); Scanner keyIn = new Scanner(System.in); String str = keyIn.nextLine(); :

Page 68: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 68

// put all letters into list as lowercase chars for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (Character.isLetter(ch)) charList.addLast( Character.toLowerCase(ch) ); }

if (isPalindrome(charList)) System.out.println("'" + str + "' is a palindrome"); else System.out.println("'" + str + "' is not a palindrome"); } // end of main()

// isPalindrome() method goes here

} // end of CheckPali class

Page 69: 241-423 ADSA: Linked Lists/5 1 241-423 Advanced Data Structures and Algorithms Objective – –implement and use linked lists Semester 2, 2013-2014 5. Linked.

241-423 ADSA : Linked Lists/5 69

Execution