SlideShare a Scribd company logo
/**
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 .pdf
rohit219406
 
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
arrowmobile
 
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
annaelctronics
 
public class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdfpublic class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdf
accostinternational
 
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
xlynettalampleyxc
 
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
cgraciela1
 
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
fantasiatheoutofthef
 
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
sales98
 
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
trishacolsyn25353
 
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
ezycolours78
 
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
Conint29
 
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
ezzi97
 
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
tesmondday29076
 
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
climatecontrolsv
 
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
info430661
 
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
sauravmanwanicp
 
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
EricvtJFraserr
 
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
fmac5
 
--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
AdrianEBJKingr
 
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
mail931892
 

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.pdf
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdf
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdfComplete the ANOVA tableSourceDFSSMSBetween Groups35.pdf
Complete the ANOVA tableSourceDFSSMSBetween Groups35.pdf
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 
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
malavshah9013
 

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

Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 

Recently uploaded (20)

Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 

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 } }