Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a...

44
1 Java linked list

Transcript of Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a...

Page 1: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

1

Java linked list

Page 2: Java linked listipc191/wiki.files/Class_Java_9.pdf · 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 - 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 knowthe 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 acollection of objects (nodes) which both carry the data we want to store and areference 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 itsnext. Last node links to NULL.

2

Page 3: Java linked listipc191/wiki.files/Class_Java_9.pdf · 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.

Circular linked list have a reference to one node which is the tailnode and all the nodes are linked together in one direction forming acircle.

▪ A singly linked list is a linear data structure where each element (node) isa separate object.

Tail

Node< T >

data nextNodeField nextNode references a Node< T > object, an object of the same <T> class .

Field data references the object of the <T> class .

Page 4: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

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

Page 5: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List - methodsN Method’s name Method’s description1 List() Constructor builds an empty linked list .2 boolean isEmpty() Returns true if this list is empty and false

otherwise. 3 Node<T> getFirst() 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

Page 6: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Outer class List - UML diagram

List<T>Node<T> firstList()boolean isEmpty()Node<T> getFirst()Node<T> insert(Node<T> pos, T x)Node<T> remove(Node<T> pos)String toString()

Class name

Class variable

Class methods

Constructor

6

Page 7: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Inner class Node - UML diagram

Node<T>private T dataprivate Node<T> nextNodeNode(T x)Node( T data, Node<T> nextNode )T getData()Node<T> getNext()Void setData( T data)Void setNext(Node<T> nextNode)String toString()

Constructors

Class variables

Class methods

Class name

Page 8: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List - basic operations

8

addFirst : The method creates a node ( “C” ) and prepends itat the beginning of the list.

Page 9: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

9

Class List - basic operations

addLast: The method appends the node ( “S” ) to the end of the list.

Page 10: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

10

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

Page 11: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

11

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

Page 12: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

12

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

Page 13: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List - implementationpublic class List<T>{

private Node<T> first; // class List attributepublic List() {

this.first = null;} // class List constructorpublic Node<T> getFirst() {

return this.first;} // getFirstpublic boolen isEmpty() {

return this.first == null;} // isEmptypublic String toString() {

String str = “ [ “;Node<T> pos = this.first;while(pos != null) {

str = str + pos.getData(); // class Node<T> methodif(pos.getNext() != null)

str = str + ”, ”;pos = pos.getNext();

} // whilestr = str + “]”;return str;

} // toString

13

Page 14: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

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

Node<T> q = new Node<T>(x); // creating new nodeif( pos == null ) {

q.setNext(this.first);this.first = q; // first element in the list

}else {

q.setNext(pos.getNext());pos.setNext(q);

} return q;

} // insertpublic Node<T> remove(Node<T> pos) {

if( this.first == pos ) {this.first = pos.getNext(); // remove first nodereturn this.first;

}else {

Node<T> prev = this.first;while(prev.getNext() != pos) // searching pos reference

prev = prev.getNext();prev.setNext(pos.getNext());return prev.getNext();

} } // remove} // class List

Note: Class Node<T>methods

14

Page 15: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List - testThis 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> studNames = 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 = studNames.insert(last,name);

} // forNode<String> p = studNames.getFirst();while(p != null ) {

if( p.getData().charAt(0) == ‘A’)System.out.println(p.getData());

p = p.getNext();} //while

} // main 15

public Node<T> insert(Node<T> pos, T x) {

Node<T> q = new Node<T>(x); if( pos == null ){

q.setNext(this.first);this.first = q; // first element in the list

}else{

q.setNext(pos.getNext());pos.setNext(q);

} return q;

} // insert

Page 16: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List – using external methodspublic static void nameA(Node<String> p){

while(p != null ) {if( p.getData().charAt(0) == 'A') // getData from Node class, charAt() from String class

System.out.println(p.getData());p = p.getNext();

} // while} // nameApublic static void main(String args[ ]){

List<String> studNames = 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 = studNames.insert(last,name);

} // forNode<String> pl = studNames.getFirst();nameA(pl); // calling method nameA from main method

} // main16

Page 17: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

External methods – “what is” questions

17

1. What is the output for the next program giving the following linked list?

public static void what(List<Integer> list){

Node<Integer> a = list.getFirst();Node<Integer> b = list.getFirst();while (b != null ) {

Node<Integer> temp = a;a = a.getNext();b = b.getNext();list.remove(temp);if (b != null)

b = b.getNext();} // while

} // what

2. What is the purpose of the what method ?

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.nextInt();while ( x != 777) {

last = ls.insert(last, x);System.out.print(" enter an integer -> ");x = reader.nextInt();

} // whileSystem.out.println(ls);what(ls); // calling what methodSystem.out.println(ls);

} // main

Page 18: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

“what is” questions - trace

18

b

a

temp a

b b

list

a

b

temp

b

b != null -> T

b != null -> T

public static void what(List<Integer> list) {Node<Integer> a = list.getFirst();Node<Integer> b = list.getFirst();while (b != null ) {

Node<Integer> temp = a;a = a.getNext();b = b.getNext();list.remove(temp);if (b != null)

b = b.getNext(); } // while} // what

Page 19: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

“what is” questions - solution

19

enter an integer -> 1enter an integer -> 2enter an integer -> 3enter an integer -> 4enter an integer -> 777

[ 1, 2, 3, 4 ]

[ 3, 4 ]

Linked list values

sentinel

List before calling what

List after calling what

The what method removes the first half giving in the linked list.

output

Page 20: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List methods - example1This 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[ ]){

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.nextInt();System.out.print(" enter Y-> ");int y = reader.nextInt();last = ls.insert( last, new Point(x,y) );

} // forSystem.out.println(ls);printP20(ls); // calling external method (next slide)

} // main

Building Point type linked list

Creating Point type linked list

20

Page 21: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List - method printP20public static void printP20(List<Point> lst){

Node<Point> pos = lst.getFirst();while( pos != null ) {

Point point = pos.getData();if( point.getX() + point.getY() <= 20)

System.out.println(point);pos = pos.getNext();

} // while} // printP20

Class Nodemethod

Class Pointmethods

Class List method

21

Page 22: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

method main - what’s different?

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.nextInt();System.out.print(" enter Y-> ");int y = reader.nextInt();ls.insert( null, new Point(x,y) );

} // forSystem.out.println(ls);printP20(ls); // calling external method

} // main

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.nextInt();System.out.print(" enter Y-> ");int y = reader.nextInt();last= ls.insert( last, new Point(x,y) );

} // forSystem.out.println(ls);printP20(ls); // calling external method

} // main

22

Page 23: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

method main output, N = 3enter X-> 1enter Y-> 2enter X-> 3enter Y-> 4enter X-> 5enter Y-> 6[ x= 1.0 y= 2.0, x= 3.0 y= 4.0, x= 5.0 y= 6.0]

x= 1.0 y= 2.0x= 3.0 y= 4.0x= 5.0 y= 6.0

enter X-> 1enter Y-> 2enter X-> 3enter Y-> 4enter X-> 5enter 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.0x= 3.0 y= 4.0x= 1.0 y= 2.0

public Node<T> insert(Node<T> pos, T x) {

Node<T> q = new Node<T>(x); if( pos == null ) {

q.setNext(this.first);this.first = q; // first element in the list

} // ifelse{

q.setNext(pos.getNext());pos.setNext(q);

} // elsereturn q;

} // insert

23

Page 24: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

This method checks if the linked list of String type is sorted

public static boolean isSorted(List<String> lst){

Node<String> pos = lst.getFirst();while(pos != null){

if( pos.getNext() != null )if( pos.getData().compareTo(pos.getNext().getData() ) > 0 )

return false;pos = pos.getNext();

} // whilereturn true;

} // isSorted

24

Class List methods – example2

Page 25: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Example2 – 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);

} // forSystem.out.println(ls);if(isSorted(ls))

System.out.println("YES");else

System.out.println("NO");} // main

enter the string helloenter the string hienter the string wordenter the string bee[ hello, hi, word, bee ] NO

enter the string beeenter the string helloenter the string hienter the string word[ bee, hello, hi, word ] YES

25

Page 26: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List methods - example 3public static void remDuplications(List<Character> lst){

Node<Character> pos1= lst.getFirst(), pos2;while( pos1 != null ) {

char ch = pos1.getData();pos2 = pos1.getNext();while( pos2 != null ) {

if(pos2.getData() == ch)pos2 = lst.remove(pos2);

elsepos2 = pos2.getNext();

} // inner while pos1 = pos1.getNext();

} // outer while} // remDuplications

26

This method removes all duplications in Character type linked list

s a b aa z nulllst

sa b z nulllst

Page 27: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Example3 – main and executionspublic 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().charAt(0);while ( x != ‘*’ ) {

last = ls.insert(last, x);System.out.print( " enter the character -> “ );x = reader.next().charAt(0);

} // whileSystem.out.println(ls);remDuplications(ls);System.out.println(ls);

} // main

27

enter the character -> aenter the character -> senter the character -> aenter the character -> benter the character -> aenter the character -> zenter the character -> *[ a, s, a, b, a, z ] [ a, s, b, z ]

sentinel

Page 28: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

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

merge two integer type sorted linked lists ( lst1 and lst2 ) . • The merged result should be in the third linked list ( lst3 ) 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

Page 29: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Method merge2Listspublic static List<Integer> merge2Lists(List<Integer> lst1, List<Integer> lst2) {

Node<Integer> pos1 = lst1.getFirst(), pos2 = lst2.getFirst(), pos3 = null;List<Integer> lst3 = new List<Integer>();while( pos1 != null && pos2 != null ) {

if( pos1.getData() > pos2.getData() ) {pos3 = lst3.insert(pos3,pos2.getData());pos2 = pos2.getNext();

} else {

pos3 = lst3.insert(pos3,pos1.getData());pos1 = pos1.getNext();

} // if} // whilewhile(pos1 != null) {

pos3 = lst3.insert(pos3,pos1.getData());pos1 = pos1.getNext();

} // whilewhile(pos2 != null) {

pos3 = lst3.insert(pos2,pos2.getData());pos1 = pos2.getNext();

} // whilereturn lst3;

} // merge2List 29

Page 30: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

merge2Lists – main and executionspublic static void main(String[ ] args) {

List<Integer> lst1 = new List<Integer>(), lst2 = new List<Integer>();Node<Integer> last = null;System.out.print(" enter an integer -> ");int x = reader.nextInt();while ( x != 777) {

last = lst1.insert(last, x);System.out.print(" enter an integer -> ");x = reader.nextInt();

} // whilelast = null;System.out.print(" enter an integer -> ");x = reader.nextInt();while ( x != 777) {

last = lst2.insert(last, x);System.out.print(" enter an integer -> ");x = reader.nextInt();

} // whileList<Integer> lst3 = merge2Lists(ls1,ls2);System.out.println(ls1);System.out.println(ls2);System.out.println(ls3);

} // main30

enter an integer -> 1enter an integer -> 2enter an integer -> 5enter an integer -> 8enter an integer -> 9enter an integer -> 777enter an integer -> 3enter an integer -> 4enter an integer -> 7enter an integer -> 777

[ 1, 2, 5, 8, 9 ] [ 3, 4, 7 ] [ 1, 2, 3, 4, 5, 7, 8, 9 ]

lst1

lst2

sentinel

sentinel

output

Page 31: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List methods - example 4

31

This method calculates the number of different values in the integer type linked list.

public static int countDifItems(List<Integer> list) {Node<Integer> temp, pos = list.getFirst();int count = 0; // number of different valueswhile(pos != null) {

temp = pos.getNext();boolean found = false; // not foundwhile(temp != null) {

if(temp.getData() == pos.getData()) {found = true;break;

} // iftemp = temp.getNext();

} // inner whileif( !found )

count++;pos = pos.getNext();

} // outer whilereturn count;

} // countDifItems

3

Page 32: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Example4 – main and executions

32

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.nextInt();while ( x != 777){

last = ls.insert(last, x);System.out.print(" enter an integer -> ");x = reader.nextInt();

} // whileSystem.out.println(ls);System.out.println(“Count = " + countDifItems(ls));

} // main

enter an integer -> 1enter an integer -> 2enter an integer -> 1enter an integer -> 2enter an integer -> 5enter an integer -> 777[ 1, 2, 1, 2, 5 ]

Count = 3

Page 33: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List methods - example 5

33

This method checks if the linked list of integer type is circular linked list

public static boolean checkCircle(List<Integer> list){

Node<Integer> a = list.getFirst();Node<Integer> b = list.getFirst();while ( b != null ) {

a = a.getNext();b = b.getNext();if ( b != null )

b = b.getNext();else

return false;if (a == b)

return true;} // whilereturn false;

} // checkCircle

Tail

Page 34: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Example5 – main and executions

34

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.nextInt();while ( x != 777) {

last = ls.insert(last, x);System.out.print(" enter an integer -> ");x = reader.nextInt();

} //whileSystem.out.println(ls);

if(checkCircle(ls))System.out.println("YES");

elseSystem.out.println("NO");

} // main

enter an integer -> 1enter an integer -> 2enter an integer -> 3enter an integer -> 4enter an integer -> 5enter an integer -> 777[ 1, 2, 3, 4, 5 ] YES

/* building circular linked list */Node<Integer> pos = ls.getFirst();Node<Integer> first = ls.getFirst();while(pos.getNext() != null )

pos = pos.getNext(); pos.setNext(first);

enter an integer -> 1enter an integer -> 2enter an integer -> 3enter an integer -> 4enter an integer -> 5enter an integer -> 777[ 1, 2, 3, 4, 5 ] NO

Page 35: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List recursive method1

35

This method tests if the number which passed as parameter exists in thelinked list of integer type.

public static boolean what1(List<Integer> lst, int num){

boolean ans; // returned valueint temp; // help variableif( lst.isEmpty() )

ans = false;else{

temp = lst.getFirst().getData();lst.remove(lst.getFirst());ans = (temp == num) || what1(lst,num); lst.insert(null, temp);

} // if return ans;

} // what

Page 36: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Recursive methods1 debugging

36

public static boolean what1(List<Integer> lst, int num){

boolean ans; // returned valueint temp; // help variableif( lst.isEmpty() )

ans = false;else{

temp = lst.getFirst().getData();lst.remove(lst.getFirst());ans = (temp == num) || what1(lst,num);

System.out.println("before insert temp“ + lst);lst.insert(null, temp);

System.out.println(“after insert temp“ + lst);} // else return ans;

} // what1

enter an integer -> 1enter an integer -> 2enter an integer -> 3enter an integer -> 777[ 1, 2, 3 ] enter search number -> 5before 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 -> 1enter an integer -> 2enter an integer -> 3enter an integer -> 777[ 1, 2, 3 ] enter search number -> 2before insert temp [ 3 ] after insert temp [ 2, 3 ] before insert temp [ 2, 3 ] after insert temp [ 1, 2, 3 ] YES

Page 37: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Linked list recursive method2

public static int what2(Node<Integer> lst){

if ( lst == null )return 0;

Node<Integer> pos = lst.getNext();int temp = what2(pos);if( !(temp % 2 == 0) ){

System.out.println( "temp= “ + temp);System.out.println(pos.getData());

}return temp + 1;

} // what237

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 ?

Page 38: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

recursive method2 - solution

38

[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]temp = 19temp = 37temp = 55temp = 73

what2 = 9

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.nextInt();while ( x !=777) {

last = ls.insert(last, x);System.out.print(" enter an integer -> ");x = reader.nextInt();

} // whileSystem.out.println(ls);Node<Integer> first = ls.getFirst();System.out.println("what2 = " + what2(first));

} // main

This will produce the next output :

Method what2 returns the number of elements in the singly linked list.

Page 39: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Class List methods - exam question 1

39

Write the method:

public static int MaxSubList( 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', 't', 'a', 'y', 'w‘

The method MaxSubList(lst,'z','a') receives the value 5 ( lst = z, a, t, t, a ).

The method MaxSubList(lst,'w','w') receives the value 1.

The method MaxSubList(lst,'a','k') receives the value 0.

Page 40: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

Exam question - solution 1public static int MaxSubList ( List<Character> lst, char x, char y ) {

Node<Character> pos = lst.getFirst();boolean start = false; // found x valueint maxLen = 0; // largest sub-list lengthint curLen = 0; // current sub-list lengthwhile (pos != null) {

if (pos.getData() == x){

start = true;break;

} // ifpos = pos.getNext();

} // whileif (x == y)

curLen = 1;while (pos != null && start) {

if (pos.getData() == y){

maxLen += curLen;curLen = 0;

} // ifcurLen++;pos = pos.getNext();

} // whilereturn maxLen;

} // MaxSubList40

Page 41: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

: איבר בפולינום שמהווה Termמחלקה לפניך public class Term{

private int coef;private int degree;

} // Term: לייצג פולינום באמצאות רשימה מקושרת באופן הבא ניתן

. degreeומעריך בשדה coefשומר מקדם בשדה Termאיבר ברשימה מטיפוס כל . הפולינום מסודרים בסדר יורד לפי המעריך כאשר המעריך הגדול מופיע בראש הרשימהאיברי

.מעריך מופיע ברשימה לכל היותר פעם אחתכל :הרשימה , לדוגמה

3 | 5 - 2 | 4 10 | 1 3 | 0 NULL :מייצגת את הפולינום

3x^5 - 2x^4 + 10x + 3

41

Class List methods - exam question 2

Page 42: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

p2–ו p1עם ההפניות Termכתוב פקודות היוצרות עצמים של המחלקה ) ' נק10.( א.בהתאםdegreeלשדות 3-ו coef ,2לשדות 4-ו 5: והנתונים הבאים

multTerms(Term p1,Term p2)Termכתוב פעולה public static.p2-ו p1שמהווה מכפלה של עצמים p3היוצרת עצם חדש עם הפנייה

5x^2: לדוגמה * 4x^3 = 20x^5

42

Class List methods - exam question 2

Term p1 = new Term(5,2);Term p2 = new Term(4,3);

public static Term multTerms(Term p1,Term p2) {

int newCoeff = p1.getCoef() * p2.getCoef();int newDegree = p1.getDegree() + p2.getDegree();Term p3 = new Term(newCoeff, newDegree);return p3;

} // multTerms

Page 43: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

'אין קשר עם סעיף א) ' נק15.( ב: לכל אחד מאיברי הפולינום אפשר לבצע פעולת נגזרת , כידוע

אם אז, הוא מעריך של איברn–הוא מקדם של איבר ו aאיפה ש ,איבר בפולינום הוא

public static List<Term> derPolynom( List<Term> Lstפעולה כתוב ) חדשה שמייצגת אותו רשימה לרשימה שמייצגת פולינום ומחזירה Lstמקבלת כפרמטר הפנייה אשר

.אחרי ביצוע פעלת הנגזרתפולינום

:עבור רשימה , לדוגמה3 | 5 - 2 | 4 10 | 1 3 | 0 NULL

:נקבל רשימה חדשה •15 | 4 - 8 | 3 10 | 0 NULL

43

Class List methods - exam question 2

Page 44: Java linked listipc191/wiki.files/Class_Java_9.pdf · 2. Doubly linked list. Every nodes stores a reference to its previous node as well as its. next. Last node links to NULL. 2.

public static List<Term> derPolynom( List<Term> Lst ) {

List<Term> new_lst = new List<Term>(); // output listNode<Term> pos = null;Node<Term> posLst = Lst.getFirst();while( posLst != null ) {

if(posLst.getData().getDegree() != 0){

int newCoeff = posLst.getData().getCoef() * posLst.getData().getDegree();int newDegree = posLst.getData().getDegree() - 1;Term posNewTerm = new Term(newCoeff, newDegree);pos = new_lst.insert(pos,posNewTerm);posLst = posLst.getNext();

}else

posLst = posLst.getNext();} // whilereturn new_lst;

} // derPolynom 44

Class List methods - exam question 2