Java linked list 1 Java linked list definition

  • Slides: 40
Download presentation
Java linked list 1

Java linked list 1

Java linked list - definition ▪ Often in programming we are required to systematically

Java linked list - definition ▪ Often in programming we are required to systematically store some type of information. A prime example of this is to use arrays, but when you don’t know the amount of information to be stored we need a dynamic data structure. ▪ One option for us is to use a linked list. A linked list works by creating a collection of objects (nodes) which both carry the data we want to store and a reference to the next node in the list. ▪ There is more than one type of a linked list. Some different type of linked list are shown below: 1. Singly linked list. Root node links one way through all the nodes. Last node links to NULL. 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its next. Last node links to NULL. 2

Java linked list, cont. 3. Circular linked list have a reference to one node

Java linked list, cont. 3. Circular linked list have a reference to one node which is the tail node and all the nodes are linked together in one direction forming a circle. Tail ▪ A singly linked list is a linear data structure where each element (node) is a separate object. Node< T > data next. Node Field next. Node references a Node< T > object, an object of the same <T> class. Field data references the object of the <T> class.

Class List - definitions • Class List represents a singly linked list. • Each

Class List - definitions • Class List represents a singly linked list. • Each element ( we will call it a node ) of a list is comprising of two items - the data and a reference to the next node. • The last node has a reference to null. The entry point into a linked list is called the head of the list. It should be noted that head is not a separate node, but the reference to the first node. If the list is empty then the head is a null reference. • The number of nodes in a list is not fixed and can grow and shrink on demand. • In Java we are allowed to define a class (say, B) inside of another class (say, A). The class A is called the outer class, and the class B is called the inner class. The purpose of inner classes is purely to be used internally as helper classes. • The List class is the outer class and the Node class is the inner class. 4

Class List - methods N Method’s name 1 List() 2 boolean 3 Node<T> Method’s

Class List - methods N Method’s name 1 List() 2 boolean 3 Node<T> Method’s description Constructor builds an empty linked list. is. Empty() get. First() Returns true if this list is empty and false otherwise. Returns the reference to first element in this list. If list is empty returns null. 4 Node<T> insert(Node<T> pos, T x) Inserts the type T element x after the specified position pos in this list and returns the reference to inserted element x. 5 Node<T> remove(Node<T> pos) Removes the first occurrence of the specified element pos in this list and returns the next element position. We assume that pos != null. 6 String to String() Returns the string representation of linked list. 5

Outer class List - UML diagram List<T> Node<T> first List() boolean is. Empty() Node<T>

Outer class List - UML diagram List<T> Node<T> first List() boolean is. Empty() Node<T> String get. First() insert(Node<T> pos, T x) remove(Node<T> pos) to. String() Class name Class variable Constructor Class methods 6

Inner class Node - UML diagram Node<T> private T data private Node<T> next. Node(T

Inner class Node - UML diagram Node<T> private T data private Node<T> next. Node(T x) Node( T data, Node<T> next. Node ) Class name Class variables Constructors T get. Data() Node<T> get. Next() Void set. Data( T data) Void set. Next(Node<T> next. Node) String to. String() Class methods

Class List - basic operations add. First : The method creates a node (

Class List - basic operations add. First : The method creates a node ( “C” ) and prepends it at the beginning of the list. 8

Class List - basic operations add. Last: The method appends the node ( “S”

Class List - basic operations add. Last: The method appends the node ( “S” ) to the end of the list. 9

Class List - basic operations Inserting "after“: Find a node containing "key" and insert

Class List - basic operations Inserting "after“: Find a node containing "key" and insert a new node after it. In the picture below, we insert a new node after “E”: 10

Class List - basic operations Deletion: Find a node containing "key" and delete it.

Class List - basic operations Deletion: Find a node containing "key" and delete it. In the picture below we delete a node containing “ A “ 11

Class List - basic operations Traversing: Start with the head and access each node

Class List - basic operations Traversing: Start with the head and access each node until you reach null. Do not change the head reference ! 12

Class List - implementation public class List<T> { private Node<T> first; // class List

Class List - implementation public class List<T> { private Node<T> first; // class List attribute public List() { this. first = null; } // class List constructor public Node<T> get. First() { return this. first; } // get. First public boolen is. Empty() { return this. first == null; } // is. Empty public String to. String() { String str = “ [ “; Node<T> pos = this. first; while(pos != null) { str = str + pos. get. Data(); // class Node<T> method if(pos. get. Next() != null) str = str + ”, ”; pos = pos. get. Next(); } // while str = str + “]”; return str; } // to. String 13

Class List – implementation, cont. public Node<T> insert(Node<T> pos, T x) { Node<T> q

Class List – implementation, cont. public Node<T> insert(Node<T> pos, T x) { Node<T> q = new Node<T>(x); // creating new node if( pos == null ) { q. set. Next(this. first); this. first = q; // first element in the list } else { q. set. Next(pos. get. Next()); pos. set. Next(q); } return q; } // insert public Node<T> remove(Node<T> pos) { if( this. first == pos ) { this. first = pos. get. Next(); // remove first node return this. first; } else { Node<T> prev = this. first; while(prev. get. Next() != pos) // searching pos reference prev = prev. get. Next(); prev. set. Next(pos. get. Next()); return prev. get. Next(); } } // remove } // class List Note: Class Node<T> methods 14

Class List - test This program reads the names of 10 students , builds

Class List - test This program reads the names of 10 students , builds linked list and prints the names which begins with an ‘A’ character. public static void main(String args[ ]) { List<String> stud. Names = new List<String>(); Node<String> last = null; for(int i = 0; i < 10; i++) { System. out. println(“ Enter student name “); String name = reader. next(); last = stud. Names. insert(last, name); } // for Node<String> p = stud. Names. get. First(); while(p != null ) { if( p. get. Data(). char. At(0) == ‘A’) System. out. println(p. get. Data()); p = p. get. Next(); } //while } // main public Node<T> insert(Node<T> pos, T x) { Node<T> q = new Node<T>(x); if( pos == null ) { q. set. Next(this. first); this. first = q; // first element in the list } else { q. set. Next(pos. get. Next()); pos. set. Next(q); } return q; } // insert 15

Class List – using external methods public static void name. A(Node<String> p) { while(p

Class List – using external methods public static void name. A(Node<String> p) { while(p != null ) { if( p. get. Data(). char. At(0) == 'A') // get. Data from Node class, char. At() from String class System. out. println(p. get. Data()); p = p. get. Next(); } // while } // name. A public static void main(String args[ ]) { List<String> stud. Names = new List<String>(); Node<String> last = null; for(int i = 0; i < 10; i++) { System. out. println(“ Enter student name “); String name = reader. next(); last = stud. Names. insert(last, name); } // for Node<String> pl = stud. Names. get. First(); name. A(pl); // calling method name. A from main method } // main 16

External methods – “what is” questions 1. What is the output for the next

External methods – “what is” questions 1. What is the output for the next program giving the following linked list? 2. What is the purpose of the what method ? public static void what(List<Integer> list) { Node<Integer> a = list. get. First(); Node<Integer> b = list. get. First(); while (b != null ) { Node<Integer> temp = a; a = a. get. Next(); b = b. get. Next(); list. remove(temp); if (b != null) b = b. get. Next(); } // while } // what public static void main(String[ ] args) { List<Integer> ls = new List<Integer>(); Node<Integer> last = null; System. out. print(" enter an integer -> "); int x = reader. next. Int(); while ( x != 777) { last = ls. insert(last, x); System. out. print(" enter an integer -> "); x = reader. next. Int(); } // while System. out. println(ls); what(ls); // calling what method System. out. println(ls); } // main 17

“what is” questions - trace public static void what(List<Integer> list) { Node<Integer> a =

“what is” questions - trace public static void what(List<Integer> list) { Node<Integer> a = list. get. First(); Node<Integer> b = list. get. First(); while (b != null ) { Node<Integer> temp = a; a = a. get. Next(); b = b. get. Next(); list. remove(temp); if (b != null) b = b. get. Next(); } // while } // what a b temp b != null -> T b a list b b 18

“what is” questions - solution enter an integer -> 1 enter an integer ->

“what is” questions - solution enter an integer -> 1 enter an integer -> 2 enter an integer -> 3 enter an integer -> 4 enter an integer -> 777 [ 1, 2, 3, 4 ] [ 3, 4 ] The what method removes the first half giving in the linked list. Linked list values sentinel List before calling what output List after calling what 19

Class List methods - example 1 This program reads the coordinates of 10 points,

Class List methods - example 1 This program reads the coordinates of 10 points, builds linked list of Point type and prints the coordinates of points which their value sums up to 20. public static void main(String args[ ]) { Creating Point type linked list List<Point> ls = new List<Point>(); Node<Point> last = null; for( int i = 0; i < 10; i++) { System. out. print(" enter X-> "); int x = reader. next. Int(); System. out. print(" enter Y-> "); int y = reader. next. Int(); Building Point type linked list last = ls. insert( last, new Point(x, y) ); } // for System. out. println(ls); print. P 20(ls); // calling external method (next slide) } // main 20

Class List - method print. P 20 public static void print. P 20(List<Point> lst)

Class List - method print. P 20 public static void print. P 20(List<Point> lst) { Class List method Node<Point> pos = lst. get. First(); while( pos != null ) { Point point = pos. get. Data(); Class Point if( point. get. X() + point. get. Y() <= 20) methods System. out. println(point); pos = pos. get. Next(); } // while } // print. P 20 Class Node method 21

method main - what’s different? public static void main(String args[ ]) { List<Point> ls

method main - what’s different? public static void main(String args[ ]) { List<Point> ls = new List<Point>(); Node<Point> last = null; for( int i = 0; i < N; i++) { System. out. print(" enter X-> "); int x = reader. next. Int(); System. out. print(" enter Y-> "); int y = reader. next. Int(); last= ls. insert( last, new Point(x, y) ); } // for System. out. println(ls); print. P 20(ls); // calling external method } // main public static void main(String args[ ]) { List<Point> ls = new List<Point>(); for( int i = 0; i < N; i++) { System. out. print(" enter X-> "); int x = reader. next. Int(); System. out. print(" enter Y-> "); int y = reader. next. Int(); ls. insert( null, new Point(x, y) ); } // for System. out. println(ls); print. P 20(ls); // calling external method } // main 22

method main output, N = 3 enter X-> 1 public Node<T> insert(Node<T> pos, T

method main output, N = 3 enter X-> 1 public Node<T> insert(Node<T> pos, T x) enter Y-> 2 { enter X-> 3 Node<T> q = new Node<T>(x); enter Y-> 4 if( pos == null ) enter X-> 5 { enter Y-> 6 q. set. Next(this. first); [ x= 1. 0 y= 2. 0, x= 3. 0 y= 4. 0, x= 5. 0 y= 6. 0] this. first = q; // first element in the list x= 1. 0 y= 2. 0 } // if x= 3. 0 y= 4. 0 else { x= 5. 0 y= 6. 0 q. set. Next(pos. get. Next()); enter X-> 1 pos. set. Next(q); enter Y-> 2 } // else enter X-> 3 return q; enter Y-> 4 } // insert enter X-> 5 enter Y-> 6 [ x= 5. 0 y= 6. 0, x= 3. 0 y= 4. 0, x= 1. 0 y= 2. 0] x= 5. 0 y= 6. 0 x= 3. 0 y= 4. 0 x= 1. 0 y= 2. 0 23

Class List methods – example 2 This method checks if the linked list of

Class List methods – example 2 This method checks if the linked list of String type is sorted public static boolean is. Sorted(List<String> lst) { Node<String> pos = lst. get. First(); while(pos != null) { if( pos. get. Next() != null ) if( pos. get. Data(). compare. To(pos. get. Next(). get. Data() ) > 0 ) return false; pos = pos. get. Next(); } // while return true; } // is. Sorted 24

Example 2 – main and executions public static void main(String args[ ]) { List<String>

Example 2 – main and executions public static void main(String args[ ]) { List<String> ls = new List<String>(); Node<String> last = null; for(int i = 1; i < 5; i++) { System. out. print(" enter the string "); String x = reader. next(); last = ls. insert(last, x); } // for System. out. println(ls); if(is. Sorted(ls)) System. out. println("YES"); else System. out. println("NO"); } // main enter the string bee enter the string hello enter the string hi enter the string word [ bee, hello, hi, word ] YES enter the string hello enter the string hi enter the string word enter the string bee [ hello, hi, word, bee ] NO 25

Class List methods - example 3 This method removes all duplications in Character type

Class List methods - example 3 This method removes all duplications in Character type linked list public static void rem. Duplications(List<Character> lst) { Node<Character> pos 1= lst. get. First(), pos 2; while( pos 1 != null ) { lst a s a char ch = pos 1. get. Data(); pos 2 = pos 1. get. Next(); lst while( pos 2 != null ) a s { if(pos 2. get. Data() == ch) pos 2 = lst. remove(pos 2); else pos 2 = pos 2. get. Next(); } // inner while pos 1 = pos 1. get. Next(); } // outer while } // rem. Duplications b a b z z null 26

Example 3 – main and executions public static void main (String[ ] args) {

Example 3 – main and executions public static void main (String[ ] args) { List<Character> ls = new List<Character>(); Node<Character> last = null; System. out. print( " enter the character -> “ ); char x = reader. next(). char. At(0); while ( x != ‘*’ ) { last = ls. insert(last, x); System. out. print( " enter the character -> “ ); x = reader. next(). char. At(0); } // while System. out. println(ls); rem. Duplications(ls); System. out. println(ls); } // main enter the character -> enter the character -> [ a, s, a, b, a, z ] [ a, s, b, z ] a s a b a z * sentinel 27

Merging two linked list • Write a Java program that contains a method with

Merging two linked list • Write a Java program that contains a method with the capability to merge two integer type sorted linked lists ( lst 1 and lst 2 ). • The merged result should be in the third linked list ( lst 3 ) that is in sorted order. Do not destroy the original lists. • Your program should output the content of three linked lists to show the program performs properly. 28

Method merge 2 Lists public static List<Integer> merge 2 Lists(List<Integer> lst 1, List<Integer> lst

Method merge 2 Lists public static List<Integer> merge 2 Lists(List<Integer> lst 1, List<Integer> lst 2) Node<Integer> pos 1 = lst 1. get. First(), pos 2 = lst 1. get. First(), pos 3 = null; List<Integer> lst 3 = new List<Integer>(); while( pos 1 != null && pos 2 != null ) { if( pos 1. get. Data() > pos 2. get. Data() ) { pos 3 = lst 3. insert(pos 3, pos 2. get. Data()); pos 2 = pos 2. get. Next(); } else { pos 3 = lst 3. insert(pos 3, pos 1. get. Data()); pos 1 = pos 1. get. Next(); } // if } // while(pos 1 != null) { pos 3 = lst 3. insert(pos 3, pos 1. get. Data()); pos 1 = pos 1. get. Next(); } // while(pos 2 != null) { pos 3 = lst 3. insert(pos 2, pos 2. get. Data()); pos 1 = pos 2. get. Next(); } // while return lst 3; } // merge 2 List { 29

merge 2 Lists – main and executions public static void main(String[ ] args) {

merge 2 Lists – main and executions public static void main(String[ ] args) { List<Integer> lst 1 = new List<Integer>(), lst 2 = new List<Integer>(); Node<Integer> last = null; System. out. print(" enter an integer -> "); enter an integer -> int x = reader. next. Int(); enter an integer -> while ( x != 777) { enter an integer -> last = lst 1. insert(last, x); System. out. print(" enter an integer -> "); enter an integer -> x = reader. next. Int(); enter an integer -> } // while enter an integer -> last = null; enter an integer -> System. out. print(" enter an integer -> "); enter an integer -> x = reader. next. Int(); enter an integer -> while ( x != 777) { enter an integer -> last = lst 2. insert(last, x); System. out. print(" enter an integer -> "); [ 1, 2, 5, 8, 9 ] x = reader. next. Int(); [ 3, 4, 7 ] } // while [ 1, 2, 3, 4, 5, 7, 8, 9 ] List<Integer> lst 3 = merge 2 Lists(ls 1, ls 2); System. out. println(ls 1); System. out. println(ls 2); System. out. println(ls 3); } // main 1 2 5 8 9 777 3 4 7 777 lst 1 sentinel lst 2 sentinel output 30

Class List methods - example 4 This method calculates the number of different values

Class List methods - example 4 This method calculates the number of different values in the integer type linked list. public static int count. Dif. Items(List<Integer> list) { Node<Integer> temp, pos = list. get. First(); int count = 0; // number of different values while(pos != null) { temp = pos. get. Next(); boolean found = false; // not found while(temp != null) { if(temp. get. Data() == pos. get. Data()) { found = true; break; } // if temp = temp. get. Next(); } // inner while if( !found ) count++; pos = pos. get. Next(); } // outer while return count; } // count. Dif. Items 3 31

Example 4 – main and executions public static void main(String[ ] args) { List<Integer>

Example 4 – main and executions public static void main(String[ ] args) { List<Integer> ls = new List<Integer>(); Node<Integer> last = null; System. out. print(" enter an integer -> "); int x = reader. next. Int(); while ( x != 777) { last = ls. insert(last, x); System. out. print(" enter an integer -> "); x = reader. next. Int(); } // while System. out. println(ls); System. out. println(“Count = " + count. Dif. Items(ls)); } // main enter an integer -> enter an integer -> 777 [ 1, 2, 5 ] 1 2 5 Count = 3 32

Class List methods - example 5 This method checks if the linked list of

Class List methods - example 5 This method checks if the linked list of integer type is circular linked list public static boolean check. Circle(List<Integer> list) { Node<Integer> a = list. get. First(); Node<Integer> b = list. get. First(); while ( b != null ) { a = a. get. Next(); b = b. get. Next(); if ( b != null ) b = b. get. Next(); else return false; if (a == b) return true; } // while return false; } // check. Circle Tail 33

Example 5 – main and executions public static void main(String[ ] args) { List<Integer>

Example 5 – main and executions public static void main(String[ ] args) { List<Integer> ls = new List<Integer>(); Node<Integer> last = null; System. out. print(" enter an integer -> "); int x = reader. next. Int(); while ( x != 777) { last = ls. insert(last, x); System. out. print(" enter an integer -> "); x = reader. next. Int(); } //while System. out. println(ls); /* building circular linked list */ Node<Integer> pos = ls. get. First(); Node<Integer> first = ls. get. First(); while(pos. get. Next() != null ) pos = pos. get. Next(); pos. set. Next(first); if(check. Circle(ls)) System. out. println("YES"); else System. out. println("NO"); } // main enter an integer -> enter an integer -> [ 1, 2, 3, 4, 5 ] NO 1 2 3 4 5 777 enter an integer -> enter an integer -> [ 1, 2, 3, 4, 5 ] YES 1 2 3 4 5 777 34

Class List recursive method 1 This method tests if the number which passed as

Class List recursive method 1 This method tests if the number which passed as parameter exists in the linked list of integer type. public static boolean what 1(List<Integer> lst, int num) { boolean ans; // returned value int temp; // help variable if( lst. is. Empty() ) ans = false; else { temp = lst. get. First(). get. Data(); lst. remove(lst. get. First()); ans = (temp == num) || what 1(lst, num); lst. insert(null, temp); } // if return ans; } // what 35

Recursive methods 1 debugging public static boolean what 1(List<Integer> lst, int num) { boolean

Recursive methods 1 debugging public static boolean what 1(List<Integer> lst, int num) { boolean ans; // returned value int temp; // help variable if( lst. is. Empty() ) ans = false; else { temp = lst. get. First(). get. Data(); lst. remove(lst. get. First()); ans = (temp == num) || what 1(lst, num); System. out. println("before insert temp“ + lst); lst. insert(null, temp); System. out. println(“after insert temp“ + lst); } // else return ans; } // what 1 enter an integer -> 2 enter an integer -> 3 enter an integer -> 777 [ 1, 2, 3 ] enter search number -> 5 before insert temp [ ] after insert temp [ 3 ] before insert temp [ 3 ] after insert temp [ 2, 3 ] before insert temp [ 2, 3 ] after insert temp [ 1, 2, 3 ] NO enter an integer -> 1 enter an integer -> 2 enter an integer -> 3 enter an integer -> 777 [ 1, 2, 3 ] enter search number -> 2 before insert temp [ 3 ] after insert temp [ 2, 3 ] before insert temp [ 2, 3 ] after insert temp [ 1, 2, 3 ] 36 YES

Linked list recursive method 2 This method take the reference to first element in

Linked list recursive method 2 This method take the reference to first element in the singly linked list as parameter. What is the output of the method for the following linked list ? public static int what 2(Node<Integer> lst) { if ( lst == null ) return 0; Node<Integer> pos = lst. get. Next(); int temp = what 2(pos); if( !(temp % 2 == 0) ) { System. out. println( "temp= “ + temp); System. out. println(pos. get. Data()); } return temp + 1; } // what 2 37

recursive method 2 - solution public static void main(String[ ] args) { List<Integer> ls

recursive method 2 - solution public static void main(String[ ] args) { List<Integer> ls = new List<Integer>(); Node<Integer> last = null; System. out. print(" enter an integer -> "); int x = reader. next. Int(); while ( x !=777) { last = ls. insert(last, x); System. out. print(" enter an integer -> "); x = reader. next. Int(); } // while System. out. println(ls); Node<Integer> first = ls. get. First(); System. out. println("what 2 = " + what 2(first)); } // main This will produce the next output : [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] temp = 1 9 temp = 3 7 temp = 5 5 temp = 7 3 what 2 = 9 Method what 2 returns the number of elements in the singly linked list. 38

Class List methods - exam question Write the method: public static int Max. Sub.

Class List methods - exam question Write the method: public static int Max. Sub. List( List<Character> lst, char x, char y ) The method receives the length of the largest sub-list, which can be found between characters x and y. If such sub-list is not found the method receives 0. For example: If we have the following list: lst = 'a', 'd', 'z', 'a', 't', 'a', 'y', 'w‘ The method Max. Sub. List(lst, 'z', 'a') receives the value 5 ( lst = z, a, t, t, a ). The method Max. Sub. List(lst, 'w') receives the value 1. The method Max. Sub. List(lst, 'a', 'k') receives the value 0. 39

Exam question - solution public static int Max. Sub. List ( List<Character> lst, char

Exam question - solution public static int Max. Sub. List ( List<Character> lst, char x, char y ) { Node<Character> pos = lst. get. First(); boolean start = false; // found x value int max. Len = 0; // largest sub-list length int cur. Len = 0; // current sub-list length while (pos != null) { if (pos. get. Data() == x) { start = true; break; } // if pos = pos. get. Next(); } // while if (x == y) cur. Len = 1; while (pos != null && start) { if (pos. get. Data() == y) { max. Len += cur. Len; cur. Len = 0; } // if cur. Len++; pos = pos. get. Next(); } // while return max. Len; } // Max. Sub. List 40