Study the recursive instance method length()of MyLinkedList2 class and its associated auxiliary method. Then solve (a), (b), and (c) below in a similar way:
(a) Convert the method public Element find(Object obj)of MyLinkedList2 class to a recursive one. Use an auxiliary private method.
(b) Convert the method public String toString( )of MyLinkedList2 class to a recursive one such that it returns the string representation of a linked list in the form:
{ValueDatum1 valueDatum2 valueDatum3 . . . valueDatumN-1 valueDatumN}
Use an auxiliary private method.
(c) Convert the method public insertBefore(Object obj)of MyLinkedList2.Element class to a recursive one. Use an auxiliary private method.
(d) Use the given test program TestMyLinkedList2.java to test your recursive methods.
public class MyLinkedList2 {
protected Element head;
protected Element tail;
public int length(){
return auxLength(head);
}
private int auxLength(Element element){
if(element == null)
return 0;
else
return 1 + auxLength(element.next);
}
public void purge(){
head = null;
tail = null;
}
public Element getHead(){
return head;
}
public Element getTail(){
return tail;
}
public boolean isEmpty(){
return head == null;
}
public Object getFirst(){
if(head == null)
throw new ListEmptyException();
else
return head.datum;
}
public Object getLast(){
if(tail == null)
throw new ListEmptyException();
else
return tail.datum;
}
public void prepend(Object obj){
Element element = new Element(obj, head);
if(head == null)
tail = element;
head = element;
}
public void append(Object obj){
Element element = new Element(obj, null);
if(head == null)
head = element;
else
tail.next = element;
tail = element;
}
public void assign(MyLinkedList2 linkedlist){
if(linkedlist != this) {
purge();
Element element = linkedlist.head;
while (element != null) {
append(element.datum);
element = element.next;
}
}
}
public void extract(Object obj){
Element element = head;
Element lastElement = null;
while(element != null && !
element.datum.equals(obj)){
lastElement = element;
element = element.next;
}
if(element == null)
throw new IllegalArgumentException("item not found");
if(element == head)
head = element.next;
else
lastElement.next = element.next;
if(element == tail)
tail = lastElement;
}
public void extractFirst(){
if(head == null)
throw new IllegalArgumentException("item not found");
head = head.next;
if(head == null)
tail = null;
}
public void extractLast() {
if(tail == null)
throw new IllegalArgumentException("item not found");
if(head == tail)
head = tail = null;
else {
Element previous = head;
while (previous.next != tail)
previous = previous.next;
previous.next = null;
tail = previous;
}
}
public String toString(){
String s = "{";
boolean first = true;
Element element = head;
while (element != null){
if(first){
first = false;
s += element.datum;
}
else
s += ", "+element.datum;
element = element.next;
}
s += "}";
return s;
}
public Element find(Object obj){
Element element = head;
while(element != null){
if(element.datum.equals(obj))
return element;
element = element.next;
}
return null;
}
void append(Integer integer) {
throw new UnsupportedOperationException("Not supported yet."); //To
change body of generated methods, choose Tools | Templates.
}
public final class Element{
Object datum;
Element next;
Element(Object obj, Element element){
datum = obj;
next = element;
}
public Object getDatum(){
return datum;
}
public Element getNext(){
return next;
}
public void insertAfter(Object obj){
next = new Element(obj, next);
if(this == tail)
tail = next;
}
public void insertBefore(Object obj){
Element element = new Element(obj, this);
if(this == head){
head = element;
return;
}
Element previousElement = head;
while(previousElement != null && previousElement.next !=
this){
previousElement =
previousElement.next;
}
previousElement.next = element;
}
public void extract(){
Element element = null;
if(this == head)
head = next;
else{
element = head;
while(element != null && element.next != this){
element =
element.next;
}
if(element == null)
throw new InvalidOperationException();
element.next = next;
}
if(this == tail)
tail = element;
}
}
}
--------------------
import java.util.Scanner;
import lab5.*;
public class TestMyLinkedList2
{
public static void main(String[] args){
Scanner stdin = new
Scanner(System.in);
MyLinkedList2 list = new
MyLinkedList2();
int i = 1;
String inputLine;
System.out.print("Enter integer
value#"+ i+ " (or press q to quit): ");
while(stdin.hasNextInt()){
list.append(new
Integer(stdin.nextInt()));
System.out.print("Enter integer
value#"+ ++i + " (or press q to quit): ");
}
stdin.next(); // discard the
character used to terminate the above loop
System.out.println("The list is: "
+ list);
System.out.println("The list's
length is: " + list.length());
if(! list.isEmpty()){
System.out.print("Enter the integer value to be searched for:
");
MyLinkedList2.Element element =
list.find(new Integer(stdin.nextInt()));
if(element ==
null)
System.out.println("NOT FOUND");
else{
System.out.println("FOUND");
System.out.print("Enter the integer value to be inserted before the
found element: ");
element.insertBefore(new Integer(stdin.nextInt()));
System.out.println("The list is: " + list);
}
}
}
}
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
// MyLinkedList2.java (modified)
public class MyLinkedList2 {
protected Element head;
protected Element tail;
public int length() {
return auxLength(head);
}
private int auxLength(Element element) {
if (element == null)
return 0;
else
return 1 + auxLength(element.next);
}
public void purge() {
head = null;
tail = null;
}
public Element getHead() {
return head;
}
public Element getTail() {
return tail;
}
public boolean isEmpty() {
return head == null;
}
public Object getFirst() {
if (head == null)
throw new ListEmptyException();
else
return head.datum;
}
public Object getLast() {
if (tail == null)
throw new ListEmptyException();
else
return tail.datum;
}
public void prepend(Object obj) {
Element element = new Element(obj, head);
if (head == null)
tail = element;
head = element;
}
public void append(Object obj) {
Element element = new Element(obj, null);
if (head == null)
head = element;
else
tail.next = element;
tail = element;
}
public void assign(MyLinkedList2 linkedlist) {
if (linkedlist != this) {
purge();
Element element = linkedlist.head;
while (element != null) {
append(element.datum);
element = element.next;
}
}
}
public void extract(Object obj) {
Element element = head;
Element lastElement = null;
while (element != null && !element.datum.equals(obj)) {
lastElement = element;
element = element.next;
}
if (element == null)
throw new IllegalArgumentException("item not found");
if (element == head)
head = element.next;
else
lastElement.next = element.next;
if (element == tail)
tail = lastElement;
}
public void extractFirst() {
if (head == null)
throw new IllegalArgumentException("item not found");
head = head.next;
if (head == null)
tail = null;
}
public void extractLast() {
if (tail == null)
throw new IllegalArgumentException("item not found");
if (head == tail)
head = tail = null;
else {
Element previous = head;
while (previous.next != tail)
previous = previous.next;
previous.next = null;
tail = previous;
}
}
public String toString() {
// calling helper method to perform recursion and return the string in
// specified form
String s = "{" + auxToString(head) + "}";
return s;
}
// method to find and return the string representation of the list using
// recursion
private String auxToString(Element element) {
if (element == null) {// empty element, base condition
return "";// returning empty string
} else {
// storing datum's string value in a String variable
String str = element.datum.toString();
// appending a white space if there is a next element
if (element.next != null) {
str += " ";
}
// appending str with auxToString() value of next element and
// returns it
return str + auxToString(element.next);
}
}
public Element find(Object obj) {
// calling auxiliary method to perform recursion and find the element
return auxFind(obj, head);
}
// actual method that does recursion to find an element with given object if
// exists
private Element auxFind(Object obj, Element element) {
if (element == null) {// base case 1
return null;// not found
}
if (element.datum.equals(obj)) {// base case 2
return element;// found
}
// recursing to find obj
return auxFind(obj, element.next);
}
void append(Integer integer) {
append((Object) integer);
}
public final class Element {
Object datum;
Element next;
Element(Object obj, Element element) {
datum = obj;
next = element;
}
public Object getDatum() {
return datum;
}
public Element getNext() {
return next;
}
public void insertAfter(Object obj) {
next = new Element(obj, next);
if (this == tail)
tail = next;
}
public void insertBefore(Object obj) {
Element element = new Element(obj, this);
if (this == head) {
head = element;
return;
}
// taking a reference to head node
Element previousElement = head;
// calling recursive function to add element before this
auxInsertBefore(previousElement, element);
}
// helper method which actually does the recursion. This will find the
// previous node of this node and adds Element toAdd as the next of that
// node
private void auxInsertBefore(Element prev, Element toAdd) {
// checking if the next node of prev is this node (base case)
if (prev.next == this) {
// found, adding toAdd element as the next of prev
prev.next = toAdd;
} else {
// recursing with next value of prev
auxInsertBefore(prev.next, toAdd);
}
}
public void extract() {
Element element = null;
if (this == head)
head = next;
else {
element = head;
while (element != null && element.next != this) {
element = element.next;
}
if (element == null)
throw new InvalidOperationException();
element.next = next;
}
if (this == tail)
tail = element;
}
}
}
/*OUTPUT of given test program*/
Enter integer value#1 (or press q to quit): 3
Enter integer value#2 (or press q to quit): 2
Enter integer value#3 (or press q to quit): 5
Enter integer value#4 (or press q to quit): 7
Enter integer value#5 (or press q to quit): 8
Enter integer value#6 (or press q to quit): q
The list is: {3 2 5 7 8}
The list's length is: 5
Enter the integer value to be searched for: 7
FOUND
Enter the integer value to be inserted before the found element: 33
The list is: {3 2 5 33 7 8}
Study the recursive instance method length()of MyLinkedList2 class and its associated auxiliary method. Then solve (a),...
Use the Summation recursive program you did in the class to also work with minus integers. For example, the sum of -3 will be -6 which is (-3)+(-2)+(-1)+0. USE THIS CODE package project5; import java.util.Scanner; public class SingleRecursion { /** Main method */ public static long sum(int n) { if (n<0) throw new IllegalArgumentException ("Can't calculate factorial of negative"); if (n==1) return 1; else if (n==0) return 1; else ...
Problem 2: based on java.util.LinkedList class, create MyStack class that should have the methods: push(), pop(), peek(), size(), isEmpty(). my linkedlist class is: public class Lab8_problem1 { private Node head, tail; private int size; public Lab8_problem1() { this.head = null; this.tail = null; this.size = 0; } //Insert a node at specifc Location public void insertAt(int value, int index) { Node newNode = new Node(); newNode.data = value; if(head == null){ head = newNode; tail = newNode; head.next...
Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...
Here is the IntegerLinkedList_incomplete
class:
public class IntegerLinkedList {
static class Node {
/** The element stored at this node */
private int element; // reference to the element stored at this node
/** A reference to the subsequent node in the list */
private Node next; // reference to the subsequent node in the list
/**
* Creates a node with the given element and next node.
*
* @param e the element to be stored
* @param n...
Add a non-recursive inorder() method to class LinkedBinaryTree<E> to traverse binary tree. Test inorder() method. Implementation in Java #########LinkedBinary Tree class######### public class LinkedBinaryTree<E> extends AbstractBinaryTree<E> { //---------------- nested Node class ---------------- /** Nested static class for a binary tree node. */ protected static class Node<E> implements Position<E> { private E element; // an element stored at this node private Node<E> parent; // a reference to the parent node (if any) private Node<E> left; // a reference to the left...
In java Write a method public void printReverse() that prints the elements of a doubly linked list in reverse. Write a method public void delete5FromTheEnd() which deletes the 5th element from end of the list. Note that if you reach the end then you have to reverse the direction of counting. In the main() method of the test class, create a randomly generated Doubly-Linked list of 10 Integers. Next, call the delete5FromTheEnd() method and print the lists iteratively until the...
In java Write a method public void printReverse() that prints the elements of a doubly linked list in reverse. Write a method public void delete5FromTheEnd() which deletes the 5th element from end of the list. Note that if you reach the end then you have to reverse the direction of counting. In the main() method of the test class, create a randomly generated Doubly-Linked list of 10 Integers. Next, call the delete5FromTheEnd() method and print the lists iteratively until the...
Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same node, etc. Write the main method to test the swapNodes method. You may need to traverse the list. package linkedlists; public class SinglyLinkedList<E> implements Cloneable { // ---------------- nested Node class...
//LinkedList
import java.util.Scanner;
public class PoD
{
public static void main( String [] args )
{
Scanner in = new Scanner( System.in );
LinkedList teamList = new LinkedList();
final int TEAM_SIZE = Integer.valueOf(in.nextLine());
for (int i=0; i<TEAM_SIZE; i++)
{
String newTeamMember = in.nextLine();
teamList.append(newTeamMember);
}
while (in.hasNext())
{
String removeMember = in.nextLine();
teamList.remove(removeMember);
}
System.out.println("FINAL TEAM:");
System.out.println(teamList);
in.close();
System.out.print("END OF OUTPUT");
}
}
===========================================================================================
//PoD
import java.util.NoSuchElementException;
/**
* A listnked list is a sequence of nodes with...
(1) Implement the countKey(T element) method, which should return a count of the number of times that the given key (the element) is found in the list. (2) Implement the indexOf(T element) method, which is similar as the indexOf method in the String class. It returns the index (the position starting from the head node) of the first occurrence of the given element, or -1, if the element does not occur in the list. You will need to track the...