Sunteți pe pagina 1din 33

CHAPTER 2 : LISTS 2.1 Introduction to Lists 2.1.1 What is Lists? 2 1 1 Wh i Li ? 2.1.2 Types of Lists Sequential Lists 2.2.

1 Implementation 2.2.2 2 2 2 Application Linked Lists 2.3.1 Implementation 231 I l t ti 2.3.2 Application Other types of Lists
Intersession May 2009 1

2.2

2.3

2.4

Introduction to List

What is List ? List is an ordered sequence of the same type elements (example: Telephone directory, students) List provides methods for manipulating elements via their indices ( l (elements index). t i d ) manipulating a specified range of elements, searching for elements access the elements delete the elements

Intersession May 2009

Introduction to List (cont.)


Type of Lists Sequential List q Arrays structure store elements in a contiguous memory

[0]

[1]

[2]

[3]

[4]

Linked List Linked structure store elements anywhere in y memory and linked by a reference/pointer

Intersession May 2009

Linked list
Linked List Linked List is a linear collection of objects (called nodes) connected by the reference links. Program accesses a linked list via a reference to the first node in list. Program accesses a subsequent nodes via the reference link stored in the previous node. efe ence sto ed t e p evious Reference in the last node of a list is set to null.
Reference link Firstnode Lastnode

null
Intersession May 2009 4

Linked list (cont)


The advantages of using Linked list: g g Appropriate data structure: when the number of data is unpredictable. unpredictable Dynamic data structure: the length f li t th l th of a list can increase or decrease as i d necessary. Simple to maintain in sorted order: by inserting each new element at proper point in the list. list
Intersession May 2009 5

Linked list (cont)


Type of Linked list structure : a) Singly Linked list each node contains one reference to the next node.

b) Doubly Linked list each node contains two references ( to the previous and to the next node)

c) Circular linked List - last node in a list contains reference to the


first node in the list.

Intersession May 2009

Linked list (cont)


Implementation of Linked List JAVA provides class LinkedList for implementing and manipulating linked list in JAVA package (java.util.*) LinkedList class in JAVA uses a doubly linked list implementation. Programmer can also create self-defined linked list by defining own linked list class to represent the node and linked list structure structure. For this course (CSC258), we will create our own linked list class using singly linked list
Intersession May 2009 7

Linked list (cont)


ListNode structure

List N d bj t Li t Node object Data - data type (primitive or ADT Class : Fields/Data : Methods : ListNode Data, Next; Constructor Retrieval methods
Intersession May 2009 8

Next R f link -Reference li k -Store reference to next node ( ListNode type)

Linked list (cont)


ListNode and LinkedList Structure
Class : Fields: ListNode Data Next

Methods : ListNode ( Object obj ) // default constructor ListNode( Object obj, ListNode nextNode ) // constructor Object getObject() // return the data ListNode getNext() // return link/reference to next data
Intersession May 2009 9

Linked list (cont)


Class : Fields: LinkedList first node last node current node

// use to traverse the list

Methods : Constructor (default & normal) isEmpty() // check whether list is empty insertAtFront(object) // insert at the front of list insertAtBack(object) // insert at the end of list removeFromFront() // delete element from front removeFromBack() F B k() // delete element from back d l t l tf b k getFirst() // get the first node getNext() // get the reference for next node

Intersession May 2009

10

Class Linked list (cont)


// class ListNode definition public class ListNode { Object data; Obj t d t ListNode next; ListNode( Object obj ) { this( obj, null ); } ListNode( Object obj ListNode nextNode ) obj, { data = obj; next = nextNode; } Object getObject() { return data; } ListNode getNext() { return next; } } // end ListNode

Intersession May 2009

11

Class Linked list (cont)


// Class LinkedList definition public class LinkedList { private ListNode firstNode; private ListNode lastNode; private Li tN d currNode; i t ListNode N d private String name; public LinkedList() { this( "list" ); }

// use t traverse the li t to t th list // name used for list // default constructor

public LinkedList(String s) // normal constructor { name = s; firstNode = lastNode = currNode = null; }


Intersession May 2009 12

Class Linked list (cont) ( )


// Check whether the list is empty, return true if the list is empty public boolean isEmpty() { return (firstNode == null); }

Intersession May 2009

13

Class Linked list (cont) ( )


/ /* Insert an object at the front of list If list is empty, firstNode and lastNode will refer to the same object. Otherwise, firstNode refers to new node. */ public void insertAtFront (Object insertItem ) { if ( isEmpty() ) firstNode = lastNode = new ListNode (insertItem); else firstNode = new ListNode (insertItem,firstNode ); }
Intersession May 2009 14

Class Linked list (cont)


// Return the first element in the list public Obj t getFirst() bli Object tFi t() { if (isEmpty()) return null; else { currNode = firstNode; return currNode.data; } }

Intersession May 2009

15

Class Li k d list (cont) Cl Linked li t ( t)

/* Return element of the next node pointed by currNode. Use together with getFirst to traverse the list */ p public Object getNext() j g () { if (currNode != lastNode) { currNode = currNode.next; return currNode.data; } else return null; }
Intersession May 2009 16

Class Linked list (cont)


/* Insert an object at the end of the list If list is empty, firstNode and lastNode will refer to the same Object. Otherwise, lastNoderefers to new node. */ / public void insertAtBack( Object insertItem ) { if ( isEmpty() ) firstNode = lastNode = new ListNode(insertItem); else lastNode = lastNode.next = new ListNode(insertItem); }

Intersession May 2009

17

Class Linked list (cont)


// Remove the first node from the List. public Object removeFromFront()throws EmptyListException { Object removeItem = null; if ( isEmpty() ) throw new EmptyListException(name); removeItem = firstNode.data; if ( firstNode.equals (lastNode)) firstNode = lastNode = null; else firstNode = firstNode next; firstNode.next; return removeItem; }
Intersession May 2009 18

Class Linked list (cont)


// Remove the last node f R th l t d from th li t the list. public Object removeFromBack( )throws EmptyListException { Object removeItem = null; if ( isEmpty() ) throw new EmptyListException(name); removeItem = lastNode.data; if ( firstNode.equals( lastNode ) ) firstNode = lastNode = null; else { ListNode current = firstNode; while ( current.next != lastNode ) current = current.next; lastNode = current; current.next = null; } return removeItem; ret rn remo eItem }
Intersession May 2009 19

Class Linked list (cont)

// class to handle the exception class EmptyListException extends RuntimeException { public EmptyListException( String name ) { super( "The " + name + " is empty" ); } }

Intersession May 2009

20

Linked list Application


Application using Linked List with primitive type
// Linked list with primitive data type p yp import javax.swing.*; public class PrimitiveLL{ public static void main(String arg[]) { LinkedList objList = new LinkedList(); String St i a ="100",b="200", c="300", d "400" "100" b "200" "300" d="400"; String out="",out1="",out2="",out3="",out4=""; objList.insertAtBack(a); objList insertAtBack(a); objList.insertAtBack(b); objList.insertAtBack(c); objList.insertAtBack(d); objList insertAtBack(d);
Intersession May 2009 21

Linked list application (cont) (cont)

// to print initial li t t i t i iti l list out1 += "Initial data in list :" + "\n" + printList(objList); objList.insertAtFront( 234 ); objList insertAtFront("234"); objList.insertAtFront("567"); // to print current list out1 += "\nCurrent data in list :" + "\n" + printList(objList);

Intersession May 2009

22

Linked list application (cont) pp (cont) (


// to calculate the summation of numbers int sum=0,num; Object data = objList.getFirst(); while(data!=null) { num = Integer.parseInt(data.toString()); sum +=num; data = objList.getNext(); } out2+="\nSummation of numbers is : " + sum;

Intersession May 2009

23

Linked list application (cont) (cont)


// remove elements from the list Object removedData; try { removedData = objList.removeFromFront(); out3 += "\n" + removedData.toString() + " removed from list; removedData = objList.removeFromBack(); out3 += "\n" + removedData.toString() + " removed from list"; g() } catch (EmptyListException e) { System.err.println("\n" + e.toString()); }

Intersession May 2009

24

Linked list application (cont) (cont)

// to print list content after removing data from list out4 += "\ndata in list after removing two elements :" + "\n" + printList(objList); out +=out1+out2+out3+out4; JOptionPane.showMessageDialog(null,out,"Result", JOptionPane.PLAIN_MESSAGE); } //end main

Intersession May 2009

25

Linked list application (cont) (cont)


// independent function/method to print the content of list public static String printList(LinkedList List) { Object printdata = List.getFirst(); String out=""; out ; while(printdata!=null) { out +=" " + printdata; p printdata = List.getNext(); g () } return out; }

} // end PrimitiveLL

Intersession May 2009

26

Linked list application (cont)


Application using ArrayList with ADT pp cat o us g ay st t public class Student { private String metric; private double gpa; public Student() { metric = "0000"; gpa = 0.0; } public Student(String m,double gp) { metric = m; gpa = gp; } public String Display( ) { String out2=""; out2 += "\nMetric No:" + metric + " Gpa:" + gpa; return out2; } public String theMetric( ) { return metric;} public double theGpa( ) { return gpa;} } // end of class student
Intersession May 2009 27

Linked list application (cont)


// use self-defined LinkedList class; import javax.swing.*; public class S d Li { bli l StudentList{ public static void main(String[] arg) { LinkedList stuList = new LinkedList(); for(int x=0;x<10;x++) { String nm = JOptionPane.showInputDialog("Enter student's metric:"); String sgpa = JOptionPane showInputDialog JOptionPane.showInputDialog ("Enter student's cgpa:"); double gpa = Double.parseDouble(sgpa); Student st = new Student(nm,gpa); ( ,gp ); stuList.add(st); } String out1="", out2="", out3=";

Intersession May 2009

28

Linked list application (cont)


// Display data in list out1 += PrintContent(stuList); JOptionPane.showMessageDialog(null,out1,"FirstList", JOptionPane.PLAIN_MESSAGE); Student st1 = new Student("2312354", 2.4); Student st2 = new Student("4444455", 3.6); stuList.add(0,st1); ( ) stuList.add(st2); // Display data after insert 2 elements out2 +=PrintContent(stuList); JOptionPane.showMessageDialog(null,out2,"List After Insert two new data",JOptionPane.PLAIN_MESSAGE);

Intersession May 2009

29

Linked list application (cont)


// Display the best student out3 +=detBestStudent(stuList); JOptionPane.showMessageDialog(null,out3,"BestStudent", JOptionPane.PLAIN_MESSAGE);

} // end main

Intersession May 2009

30

Linked list application (cont)


// independent function/method to print content of array public static String PrintContent(LinkedList List) { String out ="";Student s; if(List == null) out +="List is empty"; else { Object data = List.getFirst(); while (data != null) { s = (Student) data; out += "\nIndex :" + z + s.Display(); data = List.getNext(); } } return out; }
Intersession May 2009 31

Linked List application (cont.)


// independent f i d d t function/ method t determine the best student ti / th d to d t i th b t t d t public static String detBestStudent(LinkedList List) { Student s best; s,best; s = (Student) List.getFirst(); double bestGpa = s.theGpa(); best = s; while (s != null) { double gpa = s.theGpa(); if (gpa > bestGpa) (gp p ) { bestGpa = gpa; best = s; } s = (Student) List.getNext(); } return best.Display(); } } // end class StudentList
Intersession May 2009 32

Li k d li t application ( li ti (cont) t) Linked list


Other Applications of Linked List Inserting - insert elements at specified location in the list Searching - search a particular element in list Counting - count the number of elements in the list Sorting - sort the elements in the list (insert elements at the right location in ascending or descending order) g g )

Intersession May 2009

33

S-ar putea să vă placă și