SlideShare a Scribd company logo
1 of 18
Download to read offline
/**
The LinkedList1 class implements a Linked list.
*/
class LinkedList1
{
/**
The Node class stores a list element
and a reference to the next node.
*/
private class Node
{
String value;
Node next;
/**
Constructor.
@param val The element to store in the node.
@param n The reference to the successor node.
*/
Node(String val, Node n)
{
value = val;
next = n;
}
/**
Constructor.
@param val The element to store in the node.
*/
Node(String val)
{
// Call the other (sister) constructor.
this(val, null);
}
}
private Node first; // list head
private Node last; // last element in list
/**
Constructor.
*/
public LinkedList1()
{
first = null;
last = null;
}
/**
The isEmpty method checks to see
if the list is empty.
@return true if list is empty,
false otherwise.
*/
public boolean isEmpty()
{
return first == null;
}
/**
The size method returns the length of the list.
@return The number of elements in the list.
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
/**
The add method adds an element to
the end of the list.
@param e The value to add to the
end of the list.
*/
public void add(String e)
{
if (isEmpty())
{
first = new Node(e);
last = first;
}
else
{
// Add to end of existing list
last.next = new Node(e);
last = last.next;
}
}
/**
The add method adds an element at a position.
@param e The element to add to the list.
@param index The position at which to add
the element.
@exception IndexOutOfBoundsException When
index is out of bounds.
*/
public void add(int index, String e)
{
if (index < 0 || index > size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Index is at least 0
if (index == 0)
{
// New element goes at beginning
first = new Node(e, first);
if (last == null)
last = first;
return;
}
// Set a reference pred to point to the node that
// will be the predecessor of the new node
Node pred = first;
for (int k = 1; k <= index - 1; k++)
{
pred = pred.next;
}
// Splice in a node containing the new element
pred.next = new Node(e, pred.next);
// Is there a new last element ?
if (pred.next.next == null)
last = pred.next;
}
/**
The toString method computes the string
representation of the list.
@return The string form of the list.
*/
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + " ");
p = p.next;
}
return strBuilder.toString();
}
/**
The remove method removes the element at an index.
@param index The index of the element to remove.
@return The element removed.
@exception IndexOutOfBoundsException When index is
out of bounds.
*/
public String remove(int index)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
String element; // The element to return
if (index == 0)
{
// Removal of first item in the list
element = first.value;
first = first.next;
if (first == null)
last = null;
}
else
{
// To remove an element other than the first,
// find the predecessor of the element to
// be removed.
Node pred = first;
// Move pred forward index - 1 times
for (int k = 1; k <= index -1; k++)
pred = pred.next;
// Store the value to return
element = pred.next.value;
// Route link around the node to be removed
pred.next = pred.next.next;
// Check if pred is now last
if (pred.next == null)
last = pred;
}
return element;
}
/**
The remove method removes an element.
@param element The element to remove.
@return true if the remove succeeded,
false otherwise.
*/
public boolean remove(String element)
{
if (isEmpty())
return false;
if (element.equals(first.value))
{
// Removal of first item in the list
first = first.next;
if (first == null)
last = null;
return true;
}
// Find the predecessor of the element to remove
Node pred = first;
while (pred.next != null &&
!pred.next.value.equals(element))
{
pred = pred.next;
}
// pred.next == null OR pred.next.value is element
if (pred.next == null)
return false;
// pred.next.value is element
pred.next = pred.next.next;
// Check if pred is now last
if (pred.next == null)
last = pred;
return true;
}
public static void main(String [] args)
{
LinkedList1 ll = new LinkedList1();
ll.add("Amy");
ll.add("Bob");
ll.add(0, "Al");
ll.add(2, "Beth");
ll.add(4, "Carol");
System.out.println("The members of the list are:");
System.out.print(ll);
}
}
/**
The DLinkedList class implements a doubly
Linked list.
*/
class DLinkedList
{
/**
The Node class stores a list element
and a reference to the next node.
*/
private class Node
{
String value; // Value of a list element
Node next; // Next node in the list
Node prev; // Previous element in the list
/**
Constructor.
@param val The element to be stored in the node.
@param n The reference to the successor node.
@param p The reference to the predecessor node.
*/
Node(String val, Node n, Node p)
{
value = val;
next = n;
prev = p;
}
/**
Constructor.
@param val The element to be stored in the node.
*/
Node(String val)
{
// Just call the other (sister) constructor
this(val, null, null);
}
}
private Node first; // Head of the list
private Node last; // Last element on the list
/**
Constructor.
*/
public DLinkedList()
{
first = null;
last = null;
}
/**
The isEmpty method checks to see if the list
is empty.
@return true if list is empty, false otherwise.
*/
public boolean isEmpty()
{
return first == null;
}
/**
The size method returns the length of the list.
@return The number of elements in the list.
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
/**
The add method adds to the end of the list.
@param e The value to add.
*/
public void add(String e)
{
if (isEmpty())
{
last = new Node(e);
first = last;
}
else
{
// Add to end of existing list
last.next = new Node(e, null, last);
last = last.next;
}
}
/**
This add method adds an element at an index.
@param e The element to add to the list.
@param index The index at which to add.
@exception IndexOutOfBoundsException
When the index is out of bounds.
*/
public void add(int index, String e)
{
if (index < 0 || index > size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Index is at least 0
if (index == 0)
{
// New element goes at beginning
Node p = first; // Old first
first = new Node(e, p, null);
if (p != null)
p.prev = first;
if (last == null)
last = first;
return;
}
// pred will point to the predecessor
// of the new node.
Node pred = first;
for (int k = 1; k <= index - 1; k++)
{
pred = pred.next;
}
// Splice in a node with the new element
// We want to go from pred-- succ to
// pred--middle--succ
Node succ = pred.next;
Node middle = new Node(e, succ, pred);
pred.next = middle;
if (succ == null)
last = middle;
else
succ.prev = middle;
}
/**
The toString method computes the string
representation of the list.
@return The string representation of the
linked list.
*/
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + " ");
p = p.next;
}
return strBuilder.toString();
}
/**
The remove method removes the element
at a given position.
@param index The position of the element
to remove.
@return The element removed.
@exception IndexOutOfBoundsException When
index is out of bounds.
*/
public String remove(int index)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Locate the node targeted for removal
Node target = first;
for (int k = 1; k <= index; k++)
target = target.next;
String element = target.value; // Element to return
Node pred = target.prev; // Node before the target
Node succ = target.next; // Node after the target
// Route forward and back pointers around
// the node to be removed
if (pred == null)
first = succ;
else
pred.next = succ;
if (succ == null)
last = pred;
else
succ.prev = pred;
return element;
}
/**
The remove method removes an element from the list.
@param element The element to remove.
@return true if the element was removed, false otherwise.
*/
public boolean remove(String element)
{
if (isEmpty())
return false;
// Locate the node targeted for removal
Node target = first;
while (target != null
&& !element.equals(target.value))
target = target.next;
if (target == null)
return false;
Node pred = target.prev; // Node before the target
Node succ = target.next; // Node after the target
// Route forward and back pointers around
// the node to be removed
if (pred == null)
first = succ;
else
pred.next = succ;
if (succ == null)
last = pred;
else
succ.prev = pred;
return true;
}
public static void main(String [] args)
{
DLinkedList ll = new DLinkedList();
ll.add("Amy");
ll.add("Bob");
ll.add(0, "Al");
ll.add(2, "Beth");
ll.add(4, "Carol");
System.out.println("The elements of the list are:");
System.out.println(ll);
}
}
Find the error
Find the error in correct in class below in each of the following code segments.
// Print the second element on
// a list myList of 3 elements
Node ref = myList; ref ++ ;
ref = ref.next;
System.out.print(ref.value);
2. // Print all elements in a list myList
Node ref = myList;
while (ref.next != null) {
System.out.print(ref.value + " "); }
3. // Add a node to the beginning of
// a doubly linked list
myList myList = new Node("Abraham", myList, null);
4. // Remove the first node of a nonempty
// doubly linked list
myList myList = myList.next;
5. // The reference last points to the last
// node in a nonempty doubly linked list.
// Remove the last node from the list l
ast = last.prev;
Algorithm Workbench
1. Write a recursive method void print(Node ref) that prints the values of all ele- ments in the
linked list whose first node is ref.
2. Write a nonrecursive method reverse() that reverses the order of the elements in a list.
Assume that this method is to be added to the LinkedList1 class in this chapter.
3. Write a method reverse() as in Algorithm Workbench 2, except implement the method to call
a private recursive method Node reverse(Node list). Implement this recursive method as well.
4. Add a method String removeMin() to the LinkedList1 class in this chapter. The method
removes and returns the minimum string (according to the usual dictionary order on strings) from
the list. If the list is empty, the method returns null.
Solution
1)
public void print(Node ref){
if(ref == null){
return;
}
if(ref == first){
System.out.print(ref.val);
print(ref.next);
}
else{
System.out.print(ref.val);
print(ref.next);
}
}
-----------------------------------------------------------------------------------------
2)
public void reverse() {
Node prev = null, next = null;;
if (first == null) return;
while (true) {
next = first.getNext();
first.setNext(prev);
prev = first;
if (next == null) return;
first = next;
}
}
---------------------------------------------------------------------------------------------
3)
Node reverse(Node first) {
// checking head null or not
if ( (first==null) || (first.next == null) ) return first;
// calling recursively
Node reverse = reverse(first.next);
// pointing to last element
first.next.next = first;
// pointling last node to nu
first.next = null;
return reverse;
}
----------------------------------------------------------------------------------------------
4)
public void removeMin() {
Node mini = first;
Node tempNode = first;
Node prev = null;
while(tempNode != null) {
if(tempNode.next != null && tempNode.next.data < mini.data){
mini = tempNode.next;
prev = tempNode;
}
tempNode = tempNode.next;
}
if(mini != first) { // if head node is not minimum
prev.next = mini.next;
} else {
first = first.next; //else updating minimum value
}
}

More Related Content

Similar to The LinkedList1 class implements a Linked list. class.pdf

Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfarrowmobile
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfannaelctronics
 
public class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdfpublic class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdfaccostinternational
 
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfClass DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfxlynettalampleyxc
 
Please complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docxPlease complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docxcgraciela1
 
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdfLabProgram.javaimport java.util.NoSuchElementException;public .pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdffantasiatheoutofthef
 
Consider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfConsider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfsales98
 
Design, implement, test(In Java ) a doubly linked list ADT, using DL.pdf
Design, implement, test(In Java ) a doubly linked list ADT, using DL.pdfDesign, implement, test(In Java ) a doubly linked list ADT, using DL.pdf
Design, implement, test(In Java ) a doubly linked list ADT, using DL.pdftrishacolsyn25353
 
To complete the task, you need to fill in the missing code. I’ve inc.pdf
To complete the task, you need to fill in the missing code. I’ve inc.pdfTo complete the task, you need to fill in the missing code. I’ve inc.pdf
To complete the task, you need to fill in the missing code. I’ve inc.pdfezycolours78
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfConint29
 
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfHomework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfezzi97
 
Dividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdfDividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdftesmondday29076
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfclimatecontrolsv
 
Given below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfGiven below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfinfo430661
 
I need help implementing a Stack with this java programming assignme.pdf
I need help implementing a Stack with this java programming assignme.pdfI need help implementing a Stack with this java programming assignme.pdf
I need help implementing a Stack with this java programming assignme.pdfsauravmanwanicp
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfEricvtJFraserr
 
How do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdfHow do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdffmac5
 
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdfAdrianEBJKingr
 
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in LinkedList.javaLinkedList.java Define.pdfHow do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in LinkedList.javaLinkedList.java Define.pdfmail931892
 

Similar to The LinkedList1 class implements a Linked list. class.pdf (20)

Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
 
public class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdfpublic class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdf
 
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfClass DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
 
Please complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docxPlease complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docx
 
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdfLabProgram.javaimport java.util.NoSuchElementException;public .pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
 
Consider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfConsider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdf
 
Design, implement, test(In Java ) a doubly linked list ADT, using DL.pdf
Design, implement, test(In Java ) a doubly linked list ADT, using DL.pdfDesign, implement, test(In Java ) a doubly linked list ADT, using DL.pdf
Design, implement, test(In Java ) a doubly linked list ADT, using DL.pdf
 
To complete the task, you need to fill in the missing code. I’ve inc.pdf
To complete the task, you need to fill in the missing code. I’ve inc.pdfTo complete the task, you need to fill in the missing code. I’ve inc.pdf
To complete the task, you need to fill in the missing code. I’ve inc.pdf
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
 
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfHomework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
 
Dividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdfDividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdf
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
 
Given below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfGiven below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdf
 
I need help implementing a Stack with this java programming assignme.pdf
I need help implementing a Stack with this java programming assignme.pdfI need help implementing a Stack with this java programming assignme.pdf
I need help implementing a Stack with this java programming assignme.pdf
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
 
How do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdfHow do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdf
 
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
 
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in LinkedList.javaLinkedList.java Define.pdfHow do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
 

More from malavshah9013

gen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdf
gen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdfgen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdf
gen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdfmalavshah9013
 
Fill in parameters Public New Hash table (int initial Capacity, floa.pdf
Fill in parameters Public New Hash table (int initial Capacity, floa.pdfFill in parameters Public New Hash table (int initial Capacity, floa.pdf
Fill in parameters Public New Hash table (int initial Capacity, floa.pdfmalavshah9013
 
For Phantom Limb Syndrome, please describe the symptoms and the part .pdf
For Phantom Limb Syndrome, please describe the symptoms and the part .pdfFor Phantom Limb Syndrome, please describe the symptoms and the part .pdf
For Phantom Limb Syndrome, please describe the symptoms and the part .pdfmalavshah9013
 
Explain why the organisms that were studied by Sergei Winogradsky co.pdf
Explain why the organisms that were studied by Sergei Winogradsky co.pdfExplain why the organisms that were studied by Sergei Winogradsky co.pdf
Explain why the organisms that were studied by Sergei Winogradsky co.pdfmalavshah9013
 
Electron transport powers the first steps of photosynthesis. The fo.pdf
Electron transport powers the first steps of photosynthesis. The fo.pdfElectron transport powers the first steps of photosynthesis. The fo.pdf
Electron transport powers the first steps of photosynthesis. The fo.pdfmalavshah9013
 
Describe 5 key traits the lung cancer cells within the primary tumor.pdf
Describe 5 key traits the lung cancer cells within the primary tumor.pdfDescribe 5 key traits the lung cancer cells within the primary tumor.pdf
Describe 5 key traits the lung cancer cells within the primary tumor.pdfmalavshah9013
 
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdf
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdfComplete the ANOVA tableSourceDFSSMSBetween Groups35.pdf
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdfmalavshah9013
 
English Composition II - mutiple questions on researchQuestion 1 o.pdf
English Composition II - mutiple questions on researchQuestion 1 o.pdfEnglish Composition II - mutiple questions on researchQuestion 1 o.pdf
English Composition II - mutiple questions on researchQuestion 1 o.pdfmalavshah9013
 
Customers arrive at a bank tellers booth at a rate of 2 per minute.pdf
Customers arrive at a bank tellers booth at a rate of 2 per minute.pdfCustomers arrive at a bank tellers booth at a rate of 2 per minute.pdf
Customers arrive at a bank tellers booth at a rate of 2 per minute.pdfmalavshah9013
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfmalavshah9013
 
Wolves were hunted and poisoned to extinction in Sweden and Norway b.pdf
Wolves were hunted and poisoned to extinction in Sweden and Norway b.pdfWolves were hunted and poisoned to extinction in Sweden and Norway b.pdf
Wolves were hunted and poisoned to extinction in Sweden and Norway b.pdfmalavshah9013
 
Describe the differences between OpenPGP, PGP and GPG.Solution.pdf
Describe the differences between OpenPGP, PGP and GPG.Solution.pdfDescribe the differences between OpenPGP, PGP and GPG.Solution.pdf
Describe the differences between OpenPGP, PGP and GPG.Solution.pdfmalavshah9013
 
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdf
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdfDeclaring a PointerTo define a pointer, use an asterisk, (), in t.pdf
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdfmalavshah9013
 
Who identified three key economic “advantages” that firms should hav.pdf
Who identified three key economic “advantages” that firms should hav.pdfWho identified three key economic “advantages” that firms should hav.pdf
Who identified three key economic “advantages” that firms should hav.pdfmalavshah9013
 
Which of these is the largesta. The surface zoneb. The mixed la.pdf
Which of these is the largesta. The surface zoneb. The mixed la.pdfWhich of these is the largesta. The surface zoneb. The mixed la.pdf
Which of these is the largesta. The surface zoneb. The mixed la.pdfmalavshah9013
 
Which of the following concepts is exemplified by the story of Parus .pdf
Which of the following concepts is exemplified by the story of Parus .pdfWhich of the following concepts is exemplified by the story of Parus .pdf
Which of the following concepts is exemplified by the story of Parus .pdfmalavshah9013
 
You will be implementing the following functions. You may modify the.pdf
You will be implementing the following functions. You may modify the.pdfYou will be implementing the following functions. You may modify the.pdf
You will be implementing the following functions. You may modify the.pdfmalavshah9013
 
When Elvis swims with the current, he swims 18km in 2 hours. Against.pdf
When Elvis swims with the current, he swims 18km in 2 hours. Against.pdfWhen Elvis swims with the current, he swims 18km in 2 hours. Against.pdf
When Elvis swims with the current, he swims 18km in 2 hours. Against.pdfmalavshah9013
 
What tarsal is lateral to the medial cuneiform What tarsal is .pdf
What tarsal is lateral to the medial cuneiform What tarsal is .pdfWhat tarsal is lateral to the medial cuneiform What tarsal is .pdf
What tarsal is lateral to the medial cuneiform What tarsal is .pdfmalavshah9013
 
What is the definition of memory access timeA. The difference bet.pdf
What is the definition of memory access timeA. The difference bet.pdfWhat is the definition of memory access timeA. The difference bet.pdf
What is the definition of memory access timeA. The difference bet.pdfmalavshah9013
 

More from malavshah9013 (20)

gen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdf
gen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdfgen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdf
gen diffuses Oxygen enters a from the blood to red blood cell. the bo.pdf
 
Fill in parameters Public New Hash table (int initial Capacity, floa.pdf
Fill in parameters Public New Hash table (int initial Capacity, floa.pdfFill in parameters Public New Hash table (int initial Capacity, floa.pdf
Fill in parameters Public New Hash table (int initial Capacity, floa.pdf
 
For Phantom Limb Syndrome, please describe the symptoms and the part .pdf
For Phantom Limb Syndrome, please describe the symptoms and the part .pdfFor Phantom Limb Syndrome, please describe the symptoms and the part .pdf
For Phantom Limb Syndrome, please describe the symptoms and the part .pdf
 
Explain why the organisms that were studied by Sergei Winogradsky co.pdf
Explain why the organisms that were studied by Sergei Winogradsky co.pdfExplain why the organisms that were studied by Sergei Winogradsky co.pdf
Explain why the organisms that were studied by Sergei Winogradsky co.pdf
 
Electron transport powers the first steps of photosynthesis. The fo.pdf
Electron transport powers the first steps of photosynthesis. The fo.pdfElectron transport powers the first steps of photosynthesis. The fo.pdf
Electron transport powers the first steps of photosynthesis. The fo.pdf
 
Describe 5 key traits the lung cancer cells within the primary tumor.pdf
Describe 5 key traits the lung cancer cells within the primary tumor.pdfDescribe 5 key traits the lung cancer cells within the primary tumor.pdf
Describe 5 key traits the lung cancer cells within the primary tumor.pdf
 
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdf
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdfComplete the ANOVA tableSourceDFSSMSBetween Groups35.pdf
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdf
 
English Composition II - mutiple questions on researchQuestion 1 o.pdf
English Composition II - mutiple questions on researchQuestion 1 o.pdfEnglish Composition II - mutiple questions on researchQuestion 1 o.pdf
English Composition II - mutiple questions on researchQuestion 1 o.pdf
 
Customers arrive at a bank tellers booth at a rate of 2 per minute.pdf
Customers arrive at a bank tellers booth at a rate of 2 per minute.pdfCustomers arrive at a bank tellers booth at a rate of 2 per minute.pdf
Customers arrive at a bank tellers booth at a rate of 2 per minute.pdf
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdf
 
Wolves were hunted and poisoned to extinction in Sweden and Norway b.pdf
Wolves were hunted and poisoned to extinction in Sweden and Norway b.pdfWolves were hunted and poisoned to extinction in Sweden and Norway b.pdf
Wolves were hunted and poisoned to extinction in Sweden and Norway b.pdf
 
Describe the differences between OpenPGP, PGP and GPG.Solution.pdf
Describe the differences between OpenPGP, PGP and GPG.Solution.pdfDescribe the differences between OpenPGP, PGP and GPG.Solution.pdf
Describe the differences between OpenPGP, PGP and GPG.Solution.pdf
 
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdf
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdfDeclaring a PointerTo define a pointer, use an asterisk, (), in t.pdf
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdf
 
Who identified three key economic “advantages” that firms should hav.pdf
Who identified three key economic “advantages” that firms should hav.pdfWho identified three key economic “advantages” that firms should hav.pdf
Who identified three key economic “advantages” that firms should hav.pdf
 
Which of these is the largesta. The surface zoneb. The mixed la.pdf
Which of these is the largesta. The surface zoneb. The mixed la.pdfWhich of these is the largesta. The surface zoneb. The mixed la.pdf
Which of these is the largesta. The surface zoneb. The mixed la.pdf
 
Which of the following concepts is exemplified by the story of Parus .pdf
Which of the following concepts is exemplified by the story of Parus .pdfWhich of the following concepts is exemplified by the story of Parus .pdf
Which of the following concepts is exemplified by the story of Parus .pdf
 
You will be implementing the following functions. You may modify the.pdf
You will be implementing the following functions. You may modify the.pdfYou will be implementing the following functions. You may modify the.pdf
You will be implementing the following functions. You may modify the.pdf
 
When Elvis swims with the current, he swims 18km in 2 hours. Against.pdf
When Elvis swims with the current, he swims 18km in 2 hours. Against.pdfWhen Elvis swims with the current, he swims 18km in 2 hours. Against.pdf
When Elvis swims with the current, he swims 18km in 2 hours. Against.pdf
 
What tarsal is lateral to the medial cuneiform What tarsal is .pdf
What tarsal is lateral to the medial cuneiform What tarsal is .pdfWhat tarsal is lateral to the medial cuneiform What tarsal is .pdf
What tarsal is lateral to the medial cuneiform What tarsal is .pdf
 
What is the definition of memory access timeA. The difference bet.pdf
What is the definition of memory access timeA. The difference bet.pdfWhat is the definition of memory access timeA. The difference bet.pdf
What is the definition of memory access timeA. The difference bet.pdf
 

Recently uploaded

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 

Recently uploaded (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 

The LinkedList1 class implements a Linked list. class.pdf

  • 1. /** The LinkedList1 class implements a Linked list. */ class LinkedList1 { /** The Node class stores a list element and a reference to the next node. */ private class Node { String value; Node next; /** Constructor. @param val The element to store in the node. @param n The reference to the successor node. */ Node(String val, Node n) { value = val; next = n; } /** Constructor. @param val The element to store in the node. */ Node(String val) { // Call the other (sister) constructor.
  • 2. this(val, null); } } private Node first; // list head private Node last; // last element in list /** Constructor. */ public LinkedList1() { first = null; last = null; } /** The isEmpty method checks to see if the list is empty. @return true if list is empty, false otherwise. */ public boolean isEmpty() { return first == null; } /** The size method returns the length of the list. @return The number of elements in the list. */ public int size() {
  • 3. int count = 0; Node p = first; while (p != null) { // There is an element at p count ++; p = p.next; } return count; } /** The add method adds an element to the end of the list. @param e The value to add to the end of the list. */ public void add(String e) { if (isEmpty()) { first = new Node(e); last = first; } else { // Add to end of existing list last.next = new Node(e); last = last.next; } } /** The add method adds an element at a position. @param e The element to add to the list.
  • 4. @param index The position at which to add the element. @exception IndexOutOfBoundsException When index is out of bounds. */ public void add(int index, String e) { if (index < 0 || index > size()) { String message = String.valueOf(index); throw new IndexOutOfBoundsException(message); } // Index is at least 0 if (index == 0) { // New element goes at beginning first = new Node(e, first); if (last == null) last = first; return; } // Set a reference pred to point to the node that // will be the predecessor of the new node Node pred = first; for (int k = 1; k <= index - 1; k++) { pred = pred.next; } // Splice in a node containing the new element pred.next = new Node(e, pred.next); // Is there a new last element ?
  • 5. if (pred.next.next == null) last = pred.next; } /** The toString method computes the string representation of the list. @return The string form of the list. */ public String toString() { StringBuilder strBuilder = new StringBuilder(); // Use p to walk down the linked list Node p = first; while (p != null) { strBuilder.append(p.value + " "); p = p.next; } return strBuilder.toString(); } /** The remove method removes the element at an index. @param index The index of the element to remove. @return The element removed. @exception IndexOutOfBoundsException When index is out of bounds. */ public String remove(int index) { if (index < 0 || index >= size()) {
  • 6. String message = String.valueOf(index); throw new IndexOutOfBoundsException(message); } String element; // The element to return if (index == 0) { // Removal of first item in the list element = first.value; first = first.next; if (first == null) last = null; } else { // To remove an element other than the first, // find the predecessor of the element to // be removed. Node pred = first; // Move pred forward index - 1 times for (int k = 1; k <= index -1; k++) pred = pred.next; // Store the value to return element = pred.next.value; // Route link around the node to be removed pred.next = pred.next.next; // Check if pred is now last if (pred.next == null) last = pred; } return element; }
  • 7. /** The remove method removes an element. @param element The element to remove. @return true if the remove succeeded, false otherwise. */ public boolean remove(String element) { if (isEmpty()) return false; if (element.equals(first.value)) { // Removal of first item in the list first = first.next; if (first == null) last = null; return true; } // Find the predecessor of the element to remove Node pred = first; while (pred.next != null && !pred.next.value.equals(element)) { pred = pred.next; } // pred.next == null OR pred.next.value is element if (pred.next == null) return false; // pred.next.value is element pred.next = pred.next.next;
  • 8. // Check if pred is now last if (pred.next == null) last = pred; return true; } public static void main(String [] args) { LinkedList1 ll = new LinkedList1(); ll.add("Amy"); ll.add("Bob"); ll.add(0, "Al"); ll.add(2, "Beth"); ll.add(4, "Carol"); System.out.println("The members of the list are:"); System.out.print(ll); } } /** The DLinkedList class implements a doubly Linked list. */ class DLinkedList { /** The Node class stores a list element and a reference to the next node. */ private class Node { String value; // Value of a list element Node next; // Next node in the list Node prev; // Previous element in the list /**
  • 9. Constructor. @param val The element to be stored in the node. @param n The reference to the successor node. @param p The reference to the predecessor node. */ Node(String val, Node n, Node p) { value = val; next = n; prev = p; } /** Constructor. @param val The element to be stored in the node. */ Node(String val) { // Just call the other (sister) constructor this(val, null, null); } } private Node first; // Head of the list private Node last; // Last element on the list /** Constructor. */ public DLinkedList() { first = null; last = null;
  • 10. } /** The isEmpty method checks to see if the list is empty. @return true if list is empty, false otherwise. */ public boolean isEmpty() { return first == null; } /** The size method returns the length of the list. @return The number of elements in the list. */ public int size() { int count = 0; Node p = first; while (p != null) { // There is an element at p count ++; p = p.next; } return count; } /** The add method adds to the end of the list. @param e The value to add. */
  • 11. public void add(String e) { if (isEmpty()) { last = new Node(e); first = last; } else { // Add to end of existing list last.next = new Node(e, null, last); last = last.next; } } /** This add method adds an element at an index. @param e The element to add to the list. @param index The index at which to add. @exception IndexOutOfBoundsException When the index is out of bounds. */ public void add(int index, String e) { if (index < 0 || index > size()) { String message = String.valueOf(index); throw new IndexOutOfBoundsException(message); } // Index is at least 0 if (index == 0) { // New element goes at beginning Node p = first; // Old first
  • 12. first = new Node(e, p, null); if (p != null) p.prev = first; if (last == null) last = first; return; } // pred will point to the predecessor // of the new node. Node pred = first; for (int k = 1; k <= index - 1; k++) { pred = pred.next; } // Splice in a node with the new element // We want to go from pred-- succ to // pred--middle--succ Node succ = pred.next; Node middle = new Node(e, succ, pred); pred.next = middle; if (succ == null) last = middle; else succ.prev = middle; } /** The toString method computes the string representation of the list. @return The string representation of the linked list. */ public String toString()
  • 13. { StringBuilder strBuilder = new StringBuilder(); // Use p to walk down the linked list Node p = first; while (p != null) { strBuilder.append(p.value + " "); p = p.next; } return strBuilder.toString(); } /** The remove method removes the element at a given position. @param index The position of the element to remove. @return The element removed. @exception IndexOutOfBoundsException When index is out of bounds. */ public String remove(int index) { if (index < 0 || index >= size()) { String message = String.valueOf(index); throw new IndexOutOfBoundsException(message); } // Locate the node targeted for removal Node target = first; for (int k = 1; k <= index; k++) target = target.next;
  • 14. String element = target.value; // Element to return Node pred = target.prev; // Node before the target Node succ = target.next; // Node after the target // Route forward and back pointers around // the node to be removed if (pred == null) first = succ; else pred.next = succ; if (succ == null) last = pred; else succ.prev = pred; return element; } /** The remove method removes an element from the list. @param element The element to remove. @return true if the element was removed, false otherwise. */ public boolean remove(String element) { if (isEmpty()) return false; // Locate the node targeted for removal Node target = first; while (target != null && !element.equals(target.value)) target = target.next;
  • 15. if (target == null) return false; Node pred = target.prev; // Node before the target Node succ = target.next; // Node after the target // Route forward and back pointers around // the node to be removed if (pred == null) first = succ; else pred.next = succ; if (succ == null) last = pred; else succ.prev = pred; return true; } public static void main(String [] args) { DLinkedList ll = new DLinkedList(); ll.add("Amy"); ll.add("Bob"); ll.add(0, "Al"); ll.add(2, "Beth"); ll.add(4, "Carol"); System.out.println("The elements of the list are:"); System.out.println(ll); } } Find the error Find the error in correct in class below in each of the following code segments. // Print the second element on
  • 16. // a list myList of 3 elements Node ref = myList; ref ++ ; ref = ref.next; System.out.print(ref.value); 2. // Print all elements in a list myList Node ref = myList; while (ref.next != null) { System.out.print(ref.value + " "); } 3. // Add a node to the beginning of // a doubly linked list myList myList = new Node("Abraham", myList, null); 4. // Remove the first node of a nonempty // doubly linked list myList myList = myList.next; 5. // The reference last points to the last // node in a nonempty doubly linked list. // Remove the last node from the list l ast = last.prev; Algorithm Workbench 1. Write a recursive method void print(Node ref) that prints the values of all ele- ments in the linked list whose first node is ref. 2. Write a nonrecursive method reverse() that reverses the order of the elements in a list. Assume that this method is to be added to the LinkedList1 class in this chapter. 3. Write a method reverse() as in Algorithm Workbench 2, except implement the method to call a private recursive method Node reverse(Node list). Implement this recursive method as well. 4. Add a method String removeMin() to the LinkedList1 class in this chapter. The method removes and returns the minimum string (according to the usual dictionary order on strings) from the list. If the list is empty, the method returns null. Solution 1) public void print(Node ref){ if(ref == null){ return;
  • 17. } if(ref == first){ System.out.print(ref.val); print(ref.next); } else{ System.out.print(ref.val); print(ref.next); } } ----------------------------------------------------------------------------------------- 2) public void reverse() { Node prev = null, next = null;; if (first == null) return; while (true) { next = first.getNext(); first.setNext(prev); prev = first; if (next == null) return; first = next; } } --------------------------------------------------------------------------------------------- 3) Node reverse(Node first) { // checking head null or not if ( (first==null) || (first.next == null) ) return first; // calling recursively Node reverse = reverse(first.next); // pointing to last element first.next.next = first; // pointling last node to nu first.next = null; return reverse; }
  • 18. ---------------------------------------------------------------------------------------------- 4) public void removeMin() { Node mini = first; Node tempNode = first; Node prev = null; while(tempNode != null) { if(tempNode.next != null && tempNode.next.data < mini.data){ mini = tempNode.next; prev = tempNode; } tempNode = tempNode.next; } if(mini != first) { // if head node is not minimum prev.next = mini.next; } else { first = first.next; //else updating minimum value } }