COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode...

download COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes

of 27

  • date post

    03-Jan-2016
  • Category

    Documents

  • view

    218
  • download

    0

Embed Size (px)

Transcript of COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode...

COMP 103 Lecture 1

COMP 103Linked ListsRECAP-TODAYRECAPLinked Structures: LinkedNodeIterating and printing Linked NodesInserting and removing Linked Nodes

TODAYA second look at Linked NodeImplementing a LinkedList class#Using linked structuresThree common patterns:just step along and drop off the end (e.g. print all of a list)

look for a node and stop there (e.g. printLast).

look for a node and stop at one before that (e.g. insert, remove)Must be a node before the one we want!Can only apply to non-empty lists.Need unused node at the front, or make special case for the first node!

Where do we put these methods?#LinkedNode and LinkedListLinkedNode is a data structure (a way to represent and store data) much like an Array is a data structureWe can use LinkedNode to implement a LinkedList class, much like we can use an Array to implement an ArrayList classLinked List class wraps the LinkedNode data structure and has methods to manipulate it (add, remove, size etc), much like the way ArrayList class wraps the Array data structure and has methods to manipulate it (add, remove, size, etc)

ABABData structure: Linked Node Data structure: ArrayMy Program _____________________

LinkedList ClassArrayList Classaddremoveaddremove#Types of Lists: ArrayLists, LinkedLists

Collection

List

AbstractList

ArrayList

AbstractSequentialList

LinkedListunderlying data structure: ARRAYunderlying data structure: LINKED NODES#Making a LinkedList classclass LinkedList {

private LinkedNode head = null;

public void printList( ) {for (LinkedNode rest = head; rest != null; rest = rest.next() )System.out.printf("%s, ", rest.get());}public void printList( ) { printList(head); }

private void printList(LinkedNode list) {if (list == null) return; // As before}}

Underlying data structureIterative versionRecursive version#Separate "header" objectSeparate object to represent the list as a whole

Two different classes:List type = object with a field with pointer to first nodeNode type = (underlying) data structure to hold the items

+ An empty list is an object that you can call methods on fits with the object oriented style of programming-Half the linked list is not a List. cant share list structure so easilyBAhead head C#Inserting (iterative)/** Insert the value at position n in the list (counting from 0) Assumes list is not empty, and 0