SlideShare a Scribd company logo
practice of using and manipulating a doubly linked list and (2) practice of designing and
implementing a small recursive method. Write a program named Hw2_p3.java that implements
the following requirement:
This method receives a doubly linked list that stores integers.
It reverses order of all integers in the list.
This must be done a recursive manner.
The signature of the method must be:
public static void reverse(DoublyLinkedList intList)
You may want to write a separate method with additional parameters (refer to page 214 of the
textbook).
You may not use additional storage, such as another linked list, arrays, stacks, or queues. The
rearrangement of integers must occur within the given linked list.
An incomplete Hw2_p3.java is provided. You must complete this program.
You must use the DoublyLinkedList class that is posted along with this assignment. You must
not use the DoublyLinkedList class that is included in textbooks source code collection.
Note that you must not modify the given DoublyLinkedList class and the DoubleLinkNode class.
package LinkedList;
/*
* Copyright 2014, Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
*
* Developed for use with the book:
*
* Data Structures and Algorithms in Java, Sixth Edition
* Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
* John Wiley & Sons, 2014
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
/**
* A basic doubly linked list implementation.
*
* @author Michael T. Goodrich
* @author Roberto Tamassia
* @author Michael H. Goldwasser
*/
// modifed for a course assignment
public class DoublyLinkedList {
// instance variables of the DoublyLinkedList
/** Sentinel node at the beginning of the list */
private DoubleLinkNode header; // header sentinel
/** Sentinel node at the end of the list */
private DoubleLinkNode trailer; // trailer sentinel
/** Number of elements in the list (not including sentinels) */
private int size = 0; // number of elements in the list
/** Constructs a new empty list. */
public DoublyLinkedList() {
header = new DoubleLinkNode<>(null, null, null); // create header
trailer = new DoubleLinkNode<>(null, header, null); // trailer is preceded by header
header.setNext(trailer); // header is followed by trailer
}
public DoubleLinkNode getHeader() {return header;}
public DoubleLinkNode getTrailer() {return trailer;}
public void setHeader(DoubleLinkNode h) {header = h;}
public void setTrailer(DoubleLinkNode t) {trailer = t;}
// public accessor methods
/**
* Returns the number of elements in the linked list.
* @return number of elements in the linked list
*/
public int size() { return size; }
/**
* Tests whether the linked list is empty.
* @return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() { return size == 0; }
/**
* Returns (but does not remove) the first element of the list.
* @return element at the front of the list (or null if empty)
*/
public E first() {
if (isEmpty()) return null;
return header.getNext().getElement(); // first element is beyond header
}
/**
* Returns (but does not remove) the last element of the list.
* @return element at the end of the list (or null if empty)
*/
public E last() {
if (isEmpty()) return null;
return trailer.getPrev().getElement(); // last element is before trailer
}
// public update methods
/**
* Adds an element to the front of the list.
* @param e the new element to add
*/
public void addFirst(E e) {
addBetween(e, header, header.getNext()); // place just after the header
}
/**
* Adds an element to the end of the list.
* @param e the new element to add
*/
public void addLast(E e) {
addBetween(e, trailer.getPrev(), trailer); // place just before the trailer
}
/**
* Removes and returns the first element of the list.
* @return the removed element (or null if empty)
*/
public E removeFirst() {
if (isEmpty()) return null; // nothing to remove
return remove(header.getNext()); // first element is beyond header
}
/**
* Removes and returns the last element of the list.
* @return the removed element (or null if empty)
*/
public E removeLast() {
if (isEmpty()) return null; // nothing to remove
return remove(trailer.getPrev()); // last element is before trailer
}
/**
* Adds an element to the linked list in between the given nodes.
* The given predecessor and successor should be neighboring each
* other prior to the call.
*
* @param predecessor node just before the location where the new element is inserted
* @param successor node just after the location where the new element is inserted
*/
public void addBetween(E e, DoubleLinkNode predecessor, DoubleLinkNode successor) {
// create and link a new node
DoubleLinkNode newest = new DoubleLinkNode<>(e, predecessor, successor);
predecessor.setNext(newest);
successor.setPrev(newest);
size++;
}
/**
* Removes the given node from the list and returns its element.
* @param node the node to be removed (must not be a sentinel)
*/
public E remove(DoubleLinkNode node) {
DoubleLinkNode predecessor = node.getPrev();
DoubleLinkNode successor = node.getNext();
predecessor.setNext(successor);
successor.setPrev(predecessor);
size--;
return node.getElement();
}
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
*/
public String toString() {
StringBuilder sb = new StringBuilder("(");
DoubleLinkNode walk = header.getNext();
while (walk != trailer) {
sb.append(walk.getElement());
walk = walk.getNext();
if (walk != trailer)
sb.append(", ");
}
sb.append(")");
return sb.toString();
}
// added
// insertion sort
} //----------- end of DoublyLinkedList class -----------
public class Hw2_p3 {
// implement reverse method
// you may want to write a separate method with additional parameters, which is recursive
public static void reverse(DoublyLinkedList intList) {
// complete this method
}
// use the main method for testing
// test with arrays of different lenghts
public static void main(String[] args) {
DoublyLinkedList intList = new DoublyLinkedList<>();
int[] a = {10, 20, 30, 40, 50};
for (int i=0; i();
int[] b = {10, 20, 30, 40, 50, 60};
for (int i=0; i {
/** The element stored at this DoubleLinkNode */
private E element; // reference to the element stored at this DoubleLinkNode
/** A reference to the preceding DoubleLinkNode in the list */
private DoubleLinkNode prev; // reference to the previous DoubleLinkNode in the list
/** A reference to the subsequent DoubleLinkNode in the list */
private DoubleLinkNode next; // reference to the subsequent DoubleLinkNode in the
list
/**
* Creates a DoubleLinkNode with the given element and next DoubleLinkNode.
*
* @param e the element to be stored
* @param p reference to a DoubleLinkNode that should precede the new DoubleLinkNode
* @param n reference to a DoubleLinkNode that should follow the new DoubleLinkNode
*/
public DoubleLinkNode(E e, DoubleLinkNode p, DoubleLinkNode n) {
element = e;
prev = p;
next = n;
}
// public accessor methods
/**
* Returns the element stored at the DoubleLinkNode.
* @return the element stored at the DoubleLinkNode
*/
public E getElement() { return element; }
/**
* Returns the DoubleLinkNode that precedes this one (or null if no such DoubleLinkNode).
* @return the preceding DoubleLinkNode
*/
public DoubleLinkNode getPrev() { return prev; }
/**
* Returns the DoubleLinkNode that follows this one (or null if no such DoubleLinkNode).
* @return the following DoubleLinkNode
*/
public DoubleLinkNode getNext() { return next; }
// Update methods
/**
* Sets the DoubleLinkNode's previous reference to point to DoubleLinkNode n.
* @param p the DoubleLinkNode that should precede this one
*/
public void setPrev(DoubleLinkNode p) { prev = p; }
/**
* Sets the DoubleLinkNode's next reference to point to DoubleLinkNode n.
* @param n the DoubleLinkNode that should follow this one
*/
public void setNext(DoubleLinkNode n) { next = n; }
}
__________
package LinkedList;
/*
* Copyright 2014, Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
*
* Developed for use with the book:
*
* Data Structures and Algorithms in Java, Sixth Edition
* Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
* John Wiley & Sons, 2014
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
/**
* A basic doubly linked list implementation.
*
* @author Michael T. Goodrich
* @author Roberto Tamassia
* @author Michael H. Goldwasser
*/
// modifed for a course assignment
public class DoublyLinkedList {
// instance variables of the DoublyLinkedList
/** Sentinel node at the beginning of the list */
private DoubleLinkNode header; // header sentinel
/** Sentinel node at the end of the list */
private DoubleLinkNode trailer; // trailer sentinel
/** Number of elements in the list (not including sentinels) */
private int size = 0; // number of elements in the list
/** Constructs a new empty list. */
public DoublyLinkedList() {
header = new DoubleLinkNode<>(null, null, null); // create header
trailer = new DoubleLinkNode<>(null, header, null); // trailer is preceded by header
header.setNext(trailer); // header is followed by trailer
}
public DoubleLinkNode getHeader() {return header;}
public DoubleLinkNode getTrailer() {return trailer;}
public void setHeader(DoubleLinkNode h) {header = h;}
public void setTrailer(DoubleLinkNode t) {trailer = t;}
// public accessor methods
/**
* Returns the number of elements in the linked list.
* @return number of elements in the linked list
*/
public int size() { return size; }
/**
* Tests whether the linked list is empty.
* @return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() { return size == 0; }
/**
* Returns (but does not remove) the first element of the list.
* @return element at the front of the list (or null if empty)
*/
public E first() {
if (isEmpty()) return null;
return header.getNext().getElement(); // first element is beyond header
}
/**
* Returns (but does not remove) the last element of the list.
* @return element at the end of the list (or null if empty)
*/
public E last() {
if (isEmpty()) return null;
return trailer.getPrev().getElement(); // last element is before trailer
}
// public update methods
/**
* Adds an element to the front of the list.
* @param e the new element to add
*/
public void addFirst(E e) {
addBetween(e, header, header.getNext()); // place just after the header
}
/**
* Adds an element to the end of the list.
* @param e the new element to add
*/
public void addLast(E e) {
addBetween(e, trailer.getPrev(), trailer); // place just before the trailer
}
/**
* Removes and returns the first element of the list.
* @return the removed element (or null if empty)
*/
public E removeFirst() {
if (isEmpty()) return null; // nothing to remove
return remove(header.getNext()); // first element is beyond header
}
/**
* Removes and returns the last element of the list.
* @return the removed element (or null if empty)
*/
public E removeLast() {
if (isEmpty()) return null; // nothing to remove
return remove(trailer.getPrev()); // last element is before trailer
}
/**
* Adds an element to the linked list in between the given nodes.
* The given predecessor and successor should be neighboring each
* other prior to the call.
*
* @param predecessor node just before the location where the new element is inserted
* @param successor node just after the location where the new element is inserted
*/
public void addBetween(E e, DoubleLinkNode predecessor, DoubleLinkNode successor) {
// create and link a new node
DoubleLinkNode newest = new DoubleLinkNode<>(e, predecessor, successor);
predecessor.setNext(newest);
successor.setPrev(newest);
size++;
}
/**
* Removes the given node from the list and returns its element.
* @param node the node to be removed (must not be a sentinel)
*/
public E remove(DoubleLinkNode node) {
DoubleLinkNode predecessor = node.getPrev();
DoubleLinkNode successor = node.getNext();
predecessor.setNext(successor);
successor.setPrev(predecessor);
size--;
return node.getElement();
}
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
*/
public String toString() {
StringBuilder sb = new StringBuilder("(");
DoubleLinkNode walk = header.getNext();
while (walk != trailer) {
sb.append(walk.getElement());
walk = walk.getNext();
if (walk != trailer)
sb.append(", ");
}
sb.append(")");
return sb.toString();
}
// added
// insertion sort
} //----------- end of DoublyLinkedList class -----------

More Related Content

PDF
This is a homework assignment that has to be done in JAVA.Objectiv.pdf
PDF
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
DOCX
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
PDF
please i need help Im writing a program to test the merge sort alg.pdf
PDF
In java.Write a class called GenDoubleLinkedList which is a generi.pdf
PDF
public class CircularDoublyLinkedList-E- implements List-E- { privat.pdf
PDF
Design, implement, test(In Java ) a doubly linked list ADT, using DL.pdf
PDF
I need help implementing a Stack with this java programming assignme.pdf
This is a homework assignment that has to be done in JAVA.Objectiv.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
please i need help Im writing a program to test the merge sort alg.pdf
In java.Write a class called GenDoubleLinkedList which is a generi.pdf
public class CircularDoublyLinkedList-E- implements List-E- { privat.pdf
Design, implement, test(In Java ) a doubly linked list ADT, using DL.pdf
I need help implementing a Stack with this java programming assignme.pdf

Similar to practice of using and manipulating a doubly linked list and (2) prac.pdf (20)

PDF
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdf
PDF
in Java (ignore the last line thats hidden) Create a doubly linked l.pdf
PDF
The LinkedList1 class implements a Linked list. class.pdf
PDF
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
PDF
Using visual studio 2022- a C# windows form application- and your Doub.pdf
PDF
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
PDF
Doubly Link List
PPTX
LINKED LISTS
PDF
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
PDF
210 Linked-llists of data structure with .pdf
PDF
import java-util--- public class MyLinkedList{ public static void.pdf
PDF
For each task, submit your source java code file.(1) Objective Im.pdf
PDF
hi i have to write a java program involving link lists. i have a pro.pdf
PDF
File LinkedList.java Defines a doubly-l.pdf
PDF
here is the starter code public class LinkedListPracticeLab.pdf
PDF
linked_lists4
PPTX
Lec5-Doubly-Linked-List-24102022-110112am.pptx
PDF
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
PDF
Linked List Objective The purpose of this exercise is to cr.pdf
PDF
Objective The purpose of this exercise is to create a Linke.pdf
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdf
in Java (ignore the last line thats hidden) Create a doubly linked l.pdf
The LinkedList1 class implements a Linked list. class.pdf
Write a Java Class to Implement a Generic Linked ListYour list mus.pdf
Using visual studio 2022- a C# windows form application- and your Doub.pdf
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
Doubly Link List
LINKED LISTS
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
210 Linked-llists of data structure with .pdf
import java-util--- public class MyLinkedList{ public static void.pdf
For each task, submit your source java code file.(1) Objective Im.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
File LinkedList.java Defines a doubly-l.pdf
here is the starter code public class LinkedListPracticeLab.pdf
linked_lists4
Lec5-Doubly-Linked-List-24102022-110112am.pptx
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
Linked List Objective The purpose of this exercise is to cr.pdf
Objective The purpose of this exercise is to create a Linke.pdf
Ad

More from rd1742 (20)

PDF
PR RESEARCHCriticize any advertisement of choice. ( Billboard, .pdf
PDF
Post a paper of at least 1,000 words to cover the followingDescri.pdf
PDF
Por lo general, las oportunidades y amenazas externas son ...........pdf
PDF
Por lo general, todo lo siguiente debe incluirse como ingreso sujeto.pdf
PDF
por favor ayuda dar pulgares arriba. Caso de estudio Empresas ex.pdf
PDF
PMBOK 7e emphasizes the need for project leaders�and, ideally, all p.pdf
PDF
POOL=1 if house has a pool, 0 otherwise FPLACE =1 if house has a firep.pdf
PDF
Poison Ivy - Pamela Isley proven�a de una familia adinerada, aunque .pdf
PDF
Por favor conteste ambos El embargo de petr�leo de la OPEP de los .pdf
PDF
plz help 12. Assume that John and Kevin want to incorporate a busi.pdf
PDF
Population DistributionNamaJajan perhariCarlos $ .pdf
PDF
Population of Ulundi local municipality on June 30, 2022 = 250,000. .pdf
PDF
Pregunta 3 Divanee es neurocirujano en el hospital local. Sin emba.pdf
PDF
plz help 16. Assume the same facts as the prece ding question. Wha.pdf
PDF
Por favor responda a todos. S� que algunas respuestas son correctas .pdf
PDF
Por favor conteste todas las preguntas. Solo las respuestas estar�n .pdf
PDF
PREGUNTA 3 El participante m�s activo e importante en el mercado m.pdf
PDF
Pregunta 4 (4 puntos) �Cu�les de las siguientes pueden ser considera.pdf
PDF
Pregunta 4 (1 punto) Los m�todos anal�ticos son preferibles a la.pdf
PDF
Pregunta 34 Dos etapas de vida diferentes se encuentran en las pla.pdf
PR RESEARCHCriticize any advertisement of choice. ( Billboard, .pdf
Post a paper of at least 1,000 words to cover the followingDescri.pdf
Por lo general, las oportunidades y amenazas externas son ...........pdf
Por lo general, todo lo siguiente debe incluirse como ingreso sujeto.pdf
por favor ayuda dar pulgares arriba. Caso de estudio Empresas ex.pdf
PMBOK 7e emphasizes the need for project leaders�and, ideally, all p.pdf
POOL=1 if house has a pool, 0 otherwise FPLACE =1 if house has a firep.pdf
Poison Ivy - Pamela Isley proven�a de una familia adinerada, aunque .pdf
Por favor conteste ambos El embargo de petr�leo de la OPEP de los .pdf
plz help 12. Assume that John and Kevin want to incorporate a busi.pdf
Population DistributionNamaJajan perhariCarlos $ .pdf
Population of Ulundi local municipality on June 30, 2022 = 250,000. .pdf
Pregunta 3 Divanee es neurocirujano en el hospital local. Sin emba.pdf
plz help 16. Assume the same facts as the prece ding question. Wha.pdf
Por favor responda a todos. S� que algunas respuestas son correctas .pdf
Por favor conteste todas las preguntas. Solo las respuestas estar�n .pdf
PREGUNTA 3 El participante m�s activo e importante en el mercado m.pdf
Pregunta 4 (4 puntos) �Cu�les de las siguientes pueden ser considera.pdf
Pregunta 4 (1 punto) Los m�todos anal�ticos son preferibles a la.pdf
Pregunta 34 Dos etapas de vida diferentes se encuentran en las pla.pdf
Ad

Recently uploaded (20)

PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Classroom Observation Tools for Teachers
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Presentation on HIE in infants and its manifestations
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
01-Introduction-to-Information-Management.pdf
A systematic review of self-coping strategies used by university students to ...
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
GDM (1) (1).pptx small presentation for students
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Microbial diseases, their pathogenesis and prophylaxis
2.FourierTransform-ShortQuestionswithAnswers.pdf
Cell Structure & Organelles in detailed.
Classroom Observation Tools for Teachers
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
RMMM.pdf make it easy to upload and study
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Presentation on HIE in infants and its manifestations
Module 4: Burden of Disease Tutorial Slides S2 2025
102 student loan defaulters named and shamed – Is someone you know on the list?
Final Presentation General Medicine 03-08-2024.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Chinmaya Tiranga quiz Grand Finale.pdf
01-Introduction-to-Information-Management.pdf

practice of using and manipulating a doubly linked list and (2) prac.pdf

  • 1. practice of using and manipulating a doubly linked list and (2) practice of designing and implementing a small recursive method. Write a program named Hw2_p3.java that implements the following requirement: This method receives a doubly linked list that stores integers. It reverses order of all integers in the list. This must be done a recursive manner. The signature of the method must be: public static void reverse(DoublyLinkedList intList) You may want to write a separate method with additional parameters (refer to page 214 of the textbook). You may not use additional storage, such as another linked list, arrays, stacks, or queues. The rearrangement of integers must occur within the given linked list. An incomplete Hw2_p3.java is provided. You must complete this program. You must use the DoublyLinkedList class that is posted along with this assignment. You must not use the DoublyLinkedList class that is included in textbooks source code collection. Note that you must not modify the given DoublyLinkedList class and the DoubleLinkNode class. package LinkedList; /* * Copyright 2014, Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser * * Developed for use with the book: * * Data Structures and Algorithms in Java, Sixth Edition * Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser * John Wiley & Sons, 2014 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version.
  • 2. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ /** * A basic doubly linked list implementation. * * @author Michael T. Goodrich * @author Roberto Tamassia * @author Michael H. Goldwasser */ // modifed for a course assignment public class DoublyLinkedList { // instance variables of the DoublyLinkedList /** Sentinel node at the beginning of the list */ private DoubleLinkNode header; // header sentinel /** Sentinel node at the end of the list */ private DoubleLinkNode trailer; // trailer sentinel /** Number of elements in the list (not including sentinels) */ private int size = 0; // number of elements in the list /** Constructs a new empty list. */ public DoublyLinkedList() { header = new DoubleLinkNode<>(null, null, null); // create header trailer = new DoubleLinkNode<>(null, header, null); // trailer is preceded by header header.setNext(trailer); // header is followed by trailer } public DoubleLinkNode getHeader() {return header;} public DoubleLinkNode getTrailer() {return trailer;} public void setHeader(DoubleLinkNode h) {header = h;} public void setTrailer(DoubleLinkNode t) {trailer = t;} // public accessor methods
  • 3. /** * Returns the number of elements in the linked list. * @return number of elements in the linked list */ public int size() { return size; } /** * Tests whether the linked list is empty. * @return true if the linked list is empty, false otherwise */ public boolean isEmpty() { return size == 0; } /** * Returns (but does not remove) the first element of the list. * @return element at the front of the list (or null if empty) */ public E first() { if (isEmpty()) return null; return header.getNext().getElement(); // first element is beyond header } /** * Returns (but does not remove) the last element of the list. * @return element at the end of the list (or null if empty) */ public E last() { if (isEmpty()) return null; return trailer.getPrev().getElement(); // last element is before trailer } // public update methods /** * Adds an element to the front of the list. * @param e the new element to add */ public void addFirst(E e) { addBetween(e, header, header.getNext()); // place just after the header } /** * Adds an element to the end of the list.
  • 4. * @param e the new element to add */ public void addLast(E e) { addBetween(e, trailer.getPrev(), trailer); // place just before the trailer } /** * Removes and returns the first element of the list. * @return the removed element (or null if empty) */ public E removeFirst() { if (isEmpty()) return null; // nothing to remove return remove(header.getNext()); // first element is beyond header } /** * Removes and returns the last element of the list. * @return the removed element (or null if empty) */ public E removeLast() { if (isEmpty()) return null; // nothing to remove return remove(trailer.getPrev()); // last element is before trailer } /** * Adds an element to the linked list in between the given nodes. * The given predecessor and successor should be neighboring each * other prior to the call. * * @param predecessor node just before the location where the new element is inserted * @param successor node just after the location where the new element is inserted */ public void addBetween(E e, DoubleLinkNode predecessor, DoubleLinkNode successor) { // create and link a new node DoubleLinkNode newest = new DoubleLinkNode<>(e, predecessor, successor); predecessor.setNext(newest); successor.setPrev(newest); size++; }
  • 5. /** * Removes the given node from the list and returns its element. * @param node the node to be removed (must not be a sentinel) */ public E remove(DoubleLinkNode node) { DoubleLinkNode predecessor = node.getPrev(); DoubleLinkNode successor = node.getNext(); predecessor.setNext(successor); successor.setPrev(predecessor); size--; return node.getElement(); } /** * Produces a string representation of the contents of the list. * This exists for debugging purposes only. */ public String toString() { StringBuilder sb = new StringBuilder("("); DoubleLinkNode walk = header.getNext(); while (walk != trailer) { sb.append(walk.getElement()); walk = walk.getNext(); if (walk != trailer) sb.append(", "); } sb.append(")"); return sb.toString(); } // added // insertion sort } //----------- end of DoublyLinkedList class ----------- public class Hw2_p3 { // implement reverse method // you may want to write a separate method with additional parameters, which is recursive
  • 6. public static void reverse(DoublyLinkedList intList) { // complete this method } // use the main method for testing // test with arrays of different lenghts public static void main(String[] args) { DoublyLinkedList intList = new DoublyLinkedList<>(); int[] a = {10, 20, 30, 40, 50}; for (int i=0; i(); int[] b = {10, 20, 30, 40, 50, 60}; for (int i=0; i { /** The element stored at this DoubleLinkNode */ private E element; // reference to the element stored at this DoubleLinkNode /** A reference to the preceding DoubleLinkNode in the list */ private DoubleLinkNode prev; // reference to the previous DoubleLinkNode in the list /** A reference to the subsequent DoubleLinkNode in the list */ private DoubleLinkNode next; // reference to the subsequent DoubleLinkNode in the list /** * Creates a DoubleLinkNode with the given element and next DoubleLinkNode. * * @param e the element to be stored * @param p reference to a DoubleLinkNode that should precede the new DoubleLinkNode * @param n reference to a DoubleLinkNode that should follow the new DoubleLinkNode */ public DoubleLinkNode(E e, DoubleLinkNode p, DoubleLinkNode n) { element = e; prev = p; next = n; } // public accessor methods /**
  • 7. * Returns the element stored at the DoubleLinkNode. * @return the element stored at the DoubleLinkNode */ public E getElement() { return element; } /** * Returns the DoubleLinkNode that precedes this one (or null if no such DoubleLinkNode). * @return the preceding DoubleLinkNode */ public DoubleLinkNode getPrev() { return prev; } /** * Returns the DoubleLinkNode that follows this one (or null if no such DoubleLinkNode). * @return the following DoubleLinkNode */ public DoubleLinkNode getNext() { return next; } // Update methods /** * Sets the DoubleLinkNode's previous reference to point to DoubleLinkNode n. * @param p the DoubleLinkNode that should precede this one */ public void setPrev(DoubleLinkNode p) { prev = p; } /** * Sets the DoubleLinkNode's next reference to point to DoubleLinkNode n. * @param n the DoubleLinkNode that should follow this one */ public void setNext(DoubleLinkNode n) { next = n; } } __________ package LinkedList; /* * Copyright 2014, Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser * * Developed for use with the book: * * Data Structures and Algorithms in Java, Sixth Edition * Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser * John Wiley & Sons, 2014
  • 8. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ /** * A basic doubly linked list implementation. * * @author Michael T. Goodrich * @author Roberto Tamassia * @author Michael H. Goldwasser */ // modifed for a course assignment public class DoublyLinkedList { // instance variables of the DoublyLinkedList /** Sentinel node at the beginning of the list */ private DoubleLinkNode header; // header sentinel /** Sentinel node at the end of the list */ private DoubleLinkNode trailer; // trailer sentinel /** Number of elements in the list (not including sentinels) */ private int size = 0; // number of elements in the list /** Constructs a new empty list. */ public DoublyLinkedList() { header = new DoubleLinkNode<>(null, null, null); // create header trailer = new DoubleLinkNode<>(null, header, null); // trailer is preceded by header header.setNext(trailer); // header is followed by trailer }
  • 9. public DoubleLinkNode getHeader() {return header;} public DoubleLinkNode getTrailer() {return trailer;} public void setHeader(DoubleLinkNode h) {header = h;} public void setTrailer(DoubleLinkNode t) {trailer = t;} // public accessor methods /** * Returns the number of elements in the linked list. * @return number of elements in the linked list */ public int size() { return size; } /** * Tests whether the linked list is empty. * @return true if the linked list is empty, false otherwise */ public boolean isEmpty() { return size == 0; } /** * Returns (but does not remove) the first element of the list. * @return element at the front of the list (or null if empty) */ public E first() { if (isEmpty()) return null; return header.getNext().getElement(); // first element is beyond header } /** * Returns (but does not remove) the last element of the list. * @return element at the end of the list (or null if empty) */ public E last() { if (isEmpty()) return null; return trailer.getPrev().getElement(); // last element is before trailer } // public update methods /** * Adds an element to the front of the list. * @param e the new element to add */
  • 10. public void addFirst(E e) { addBetween(e, header, header.getNext()); // place just after the header } /** * Adds an element to the end of the list. * @param e the new element to add */ public void addLast(E e) { addBetween(e, trailer.getPrev(), trailer); // place just before the trailer } /** * Removes and returns the first element of the list. * @return the removed element (or null if empty) */ public E removeFirst() { if (isEmpty()) return null; // nothing to remove return remove(header.getNext()); // first element is beyond header } /** * Removes and returns the last element of the list. * @return the removed element (or null if empty) */ public E removeLast() { if (isEmpty()) return null; // nothing to remove return remove(trailer.getPrev()); // last element is before trailer } /** * Adds an element to the linked list in between the given nodes. * The given predecessor and successor should be neighboring each * other prior to the call. * * @param predecessor node just before the location where the new element is inserted * @param successor node just after the location where the new element is inserted */ public void addBetween(E e, DoubleLinkNode predecessor, DoubleLinkNode successor) { // create and link a new node
  • 11. DoubleLinkNode newest = new DoubleLinkNode<>(e, predecessor, successor); predecessor.setNext(newest); successor.setPrev(newest); size++; } /** * Removes the given node from the list and returns its element. * @param node the node to be removed (must not be a sentinel) */ public E remove(DoubleLinkNode node) { DoubleLinkNode predecessor = node.getPrev(); DoubleLinkNode successor = node.getNext(); predecessor.setNext(successor); successor.setPrev(predecessor); size--; return node.getElement(); } /** * Produces a string representation of the contents of the list. * This exists for debugging purposes only. */ public String toString() { StringBuilder sb = new StringBuilder("("); DoubleLinkNode walk = header.getNext(); while (walk != trailer) { sb.append(walk.getElement()); walk = walk.getNext(); if (walk != trailer) sb.append(", "); } sb.append(")"); return sb.toString(); } // added // insertion sort
  • 12. } //----------- end of DoublyLinkedList class -----------