Presentation is loading. Please wait.

Presentation is loading. Please wait.

Linked Lists CS 367 – Introduction to Data Structures.

Similar presentations


Presentation on theme: "Linked Lists CS 367 – Introduction to Data Structures."— Presentation transcript:

1 Linked Lists CS 367 – Introduction to Data Structures

2 Arrays Revisited Array advantages –easy to set-up –very fast to access Array disadvantages –cannot grow in size –time consuming to do an ordered insert have to shift lots of other data around Vectors suffer from most of these faults as well

3 Array Insert Assume the following array acfmx Now assume you want to insert ‘k’ –must first determine which slot – index 3 –must then move ‘m’ and ‘x’ down one slot this can be very time consuming for large arrays 012345678 acfkm 012345678 x

4 Array Insert Time requirements for an insert –may be very quick element goes at the end of the array –may take very long element goes at beginning of the array

5 Node Node stores a piece of data Node stores a reference to another node Example: class Node { public String name; public float grade; public Node next; }

6 Linked List Basic idea –a linked list is a chain of nodes –each node references the next node in chain –last node references null Components in a linked list –node – data to store –head – first node in the list –tail – last node in the list this is an optional component

7 Linked List John Smith 87.45 Jane Doe 87.45 Pat Thomas 87.45 HeadTail

8 Linked List Advantages –can grow to “infinite” size only constrained by the size of memory –very quick to insert or delete a node just move a few references around Disadvantage –more sophisticate to implement than array –can be very slow to search and access have to access each previous element to get the one desired –this is bad for several reasons

9 Searching a Linked List To find a particular element, search the list looking for a key –a key is a particular value that indicates the node has been found –for example node, it would be the name field Sample code public Node get(String key) { Node current; for(current=head; current != null; current=current.next) { if(current.name.equals(key)) return current; } return null; }

10 Warning MUST never lose the head of the list! –Assume the find() code for loop looked like this: for(; head != null; head=head.next) { … } this would get through the list – ONCE! –there would be no way to find the head again MUST never lose a pointer in the middle of the list! –this effectively breaks the chain – no way to put it back together

11 Breaking the List John Smith 87.45 Jane Doe 87.45 Pat Thomas 87.45 Head John Doe 87.45 Broken reference string – no way to access the rest of the list.

12 Implementing a Linked List Linked list will be represented as a class Want class to be re-usable –requires using a generic interface to the list –will use the Object class to represent data any class can be referenced by an object reference of type Object

13 compareTo() Method Method found in the Comparable interface –public int compareTo(Object obj); // signature The point of this object is to compare object obj to the current object –you must implement the code for compareTo Return values –less than 0: current object is less than obj –equal to 0: current object and obj are equal –greater than 0: current object is greater than obj

14 Simple Data Container class Person implements Comparable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public int compareTo(Object obj) { Person p = (Person)obj; return name.compareTo(p.getName()); } public String toString() { String s = new String(name + “(“ + age + “)”); return s; }

15 Generic Node Code class Node { private Object data; private Node next; public Node(Object data, Node next) { this.data = data; this.next = next; } public Object getData() { return data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } }

16 Generic Linked List Code class LinkedList { private Node head; public LinkedList() { head = null; } public void addHead(Object data); public void add(Object data); public Object getHead(); public Object get(key); public Object deleteHead(); public Object delete(key); public boolean isEmpty(); public void printList(); }

17 Possible Cases For all algorithms, consider the following cases –empty list –only one item in the list –desired node at the head of the list –desired node at the end of the list –desired node in the middle of the list

18 addHead() / add() public void addHead(Object data) { head = new Node(data, head); } public void add(Object data) { Node prev = null; Node cur = head; // find it’s place in the list – ties are done FCFS while((cur != null) && !(((Comparable)cur.getData()).compareTo(data) > 0)) { prev = cur; cur = cur.getNext(); } // create the node and adjust pointers Node tmp = new Node(data, cur); if(prev != null) { prev.setNext(tmp); } else { head = tmp; } }

19 add() Notes Need two references – previous and current –why? Must manipulate references in the proper order –consider what happens if we had used the following line for the while loop while(…) { cur = cur.getNext(); prev = cur; } –everything would be wrong

20 getHead() / get() public Object getHead() { if(head != null) { return head.getData(); } else { return null; } } public Object get(Object key) { Node tmp = head; // find the node – if it exists while((tmp != null) && (((Comparable)tmp.getData()).compareTo(key) != 0)) tmp = tmp.getNext(); if(tmp != null) { return tmp.getData(); } else { return null; } }

21 get() Notes Simply looking for a piece of data, if we find it, return a reference to it –if it’s not in the list, return null The list does not change because of a get operation Notice there is no previous or current references this time –why?

22 deleteHead() public Object deleteHead() { Object data = null; if(head != null) { data = head.getData(); head = head.getNext(); } return data; }

23 delete() public Object delete(Object key) { Node prev = null; Node cur = head; // find it in the list – if it exists while((cur != null) && (((Comparable)cur.getData()).compareTo(item) != 0)) { prev = cur; cur = cur.getNext(); } // get data, delete the node, and return the data Object data = null; if(cur != null) { data = cur.getData(); if(prev != null) { prev.setNext(cur.getNext()); } else { head = cur.getNext(); } } return data; }

24 delete() Notes Deleting a node is the most difficult (and error prone) of all linked list methods –lots of details to get right Again need to make sure all references get adjusted in the proper order –again, must move previous before current Note for C/C++ writers (this will be you some day) –need to make sure you retrieve the data before deleting the node common mistake

25 isEmpty() / printList() public boolean isEmpty() { return head == null; } public void printList() { for(Node tmp=head; tmp != null; tmp=tmp.getNext()) System.out.println(tmp.getData().toString()); } These methods are not necessary but they do come in handy

26 Simple Example class Example { public static void main(String[] args) { LinkedList list = new LinkedList(); InputStreamReader input = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(input); for(;;) { System.out.println(“Enter person’s name (type ‘exit’ to quit): “); String name = in.readLine(); if(name.equals(“exit”) break; System.out.println(“Enter person’s age: “); String age = in.readLine(); Person p = new Person(name, Integer.parseInt(age)); list.add(p); } list.printList(); }


Download ppt "Linked Lists CS 367 – Introduction to Data Structures."

Similar presentations


Ads by Google