SlideShare a Scribd company logo
Problem: Describe an algorithm for concatenating two singly linked lists L and M, into a single
list L that contains all the nodes of L followed by all the nodes of M. Modify the
SinglyLinkedList class to contain the method:
public void concatenate(SinglyLinkedList other) { ... }
PLEASE PLEASE USE THE CODE BELOW..... THANK YOU
public class SinglyLinkedList<E> implements Cloneable {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
/** The element stored at this node */
private E element; // reference to the element stored at this node
/** A reference to the subsequent node in the list */
private Node<E> 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 reference to a node that should follow the new node
*/
public Node(E e, Node<E> n) {
element = e;
next = n;
}
// Accessor methods
/**
* Returns the element stored at the node.
* @return the element stored at the node
*/
public E getElement() { return element; }
/**
* Returns the node that follows this one (or null if no such node).
* @return the following node
*/
public Node<E> getNext() { return next; }
// Modifier methods
/**
* Sets the node's next reference to point to Node n.
* @param n the node that should follow this one
*/
public void setNext(Node<E> n) { next = n; }
} //----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
/** The head node of the list */
private Node<E> head = null; // head node of the list (or null if empty)
/** The last node of the list */
private Node<E> tail = null; // last node of the list (or null if empty)
/** Number of nodes in the list */
private int size = 0; // number of nodes in the list
/** Constructs an initially empty list. */
public SinglyLinkedList() { } // constructs an initially empty list
// access 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() { // returns (but does not remove) the first element
if (isEmpty()) return null;
return head.getElement();
}
/**
* 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() { // returns (but does not remove) the last element
if (isEmpty()) return null;
return tail.getElement();
}
// update methods
/**
* Adds an element to the front of the list.
* @param e the new element to add
*/
public void addFirst(E e) { // adds element e to the front of the list
head = new Node<>(e, head); // create and link a new node
if (size == 0)
tail = head; // special case: new node becomes tail also
size++;
}
/**
* Adds an element to the end of the list.
* @param e the new element to add
*/
public void addLast(E e) { // adds element e to the end of the list
Node<E> newest = new Node<>(e, null); // node will eventually be the tail
if (isEmpty())
head = newest; // special case: previously empty list
else
tail.setNext(newest); // new node after existing tail
tail = newest; // new node becomes the tail
size++;
}
/**
* Removes and returns the first element of the list.
* @return the removed element (or null if empty)
*/
public E removeFirst() { // removes and returns the first element
if (isEmpty()) return null; // nothing to remove
E answer = head.getElement();
head = head.getNext(); // will become null if list had only one node
size--;
if (size == 0)
tail = null; // special case as list is now empty
return answer;
}
@SuppressWarnings({"unchecked"})
public boolean equals(Object o) {
if (o == null) return false;
if (getClass() != o.getClass()) return false;
SinglyLinkedList other = (SinglyLinkedList) o; // use nonparameterized type
if (size != other.size) return false;
Node walkA = head; // traverse the primary list
Node walkB = other.head; // traverse the secondary list
while (walkA != null) {
if (!walkA.getElement().equals(walkB.getElement())) return false; //mismatch
walkA = walkA.getNext();
walkB = walkB.getNext();
}
return true; // if we reach this, everything matched successfully
}
@SuppressWarnings({"unchecked"})
public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
// always use inherited Object.clone() to create the initial copy
SinglyLinkedList<E> other = (SinglyLinkedList<E>) super.clone(); // safe cast
if (size > 0) { // we need independent chain of nodes
other.head = new Node<>(head.getElement(), null);
Node<E> walk = head.getNext(); // walk through remainder of original list
Node<E> otherTail = other.head; // remember most recently created node
while (walk != null) { // make a new node storing same element
Node<E> newest = new Node<>(walk.getElement(), null);
otherTail.setNext(newest); // link previous node to this one
otherTail = newest;
walk = walk.getNext();
}
}
return other;
}
public int hashCode() {
int h = 0;
for (Node walk=head; walk != null; walk = walk.getNext()) {
h ^= walk.getElement().hashCode(); // bitwise exclusive-or with element's code
h = (h << 5) | (h >>> 27); // 5-bit cyclic shift of composite code
}
return h;
}
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
*/
public String toString() {
StringBuilder sb = new StringBuilder("(");
Node<E> walk = head;
while (walk != null) {
sb.append(walk.getElement());
if (walk != tail)
sb.append(", ");
walk = walk.getNext();
}
sb.append(")");
return sb.toString();
}
public void concatenate(SinglyLinkedList<E> other) {
............. TYPE CODE HERE.........
}
}
}

More Related Content

Similar to Problem- Describe an algorithm for concatenating two singly linked lis.pdf (20)

PDF
package linkedLists- import java-util-Iterator- --- A class representi.pdf
arcellzone
 
PDF
please i need help Im writing a program to test the merge sort alg.pdf
ezonesolutions
 
PDF
STAGE 2 The Methods 65 points Implement all the methods t.pdf
babitasingh698417
 
PDF
Add these methods to the code - -Create at least three classes such.pdf
SebastianRzuHarrisw
 
PDF
here is the starter code public class LinkedListPracticeLab.pdf
geetakannupillai1
 
PDF
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
footstatus
 
PPTX
Chapter 4 Linked List introduction lessons.pptx
MohamedAhmed686097
 
PDF
practice of using and manipulating a doubly linked list and (2) prac.pdf
rd1742
 
PDF
Fix my codeCode.pdf
Conint29
 
PDF
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
deepakangel
 
PDF
You can list anything, it doesnt matter. I just want to see code f.pdf
fashionbigchennai
 
PDF
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
arrowmobile
 
PDF
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdf
aptind
 
PDF
Use the singly linked list class introduced in the lab to implement .pdf
sales87
 
PDF
Linked List Objective The purpose of this exercise is to cr.pdf
adityacomputers001
 
PDF
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
Stewart29UReesa
 
PDF
import java-util--- public class MyLinkedList{ public static void.pdf
asarudheen07
 
DOCX
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
Komlin1
 
PDF
In this assignment you will implement insert() method for a singly l.pdf
fantasiatheoutofthef
 
PDF
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
fantasiatheoutofthef
 
package linkedLists- import java-util-Iterator- --- A class representi.pdf
arcellzone
 
please i need help Im writing a program to test the merge sort alg.pdf
ezonesolutions
 
STAGE 2 The Methods 65 points Implement all the methods t.pdf
babitasingh698417
 
Add these methods to the code - -Create at least three classes such.pdf
SebastianRzuHarrisw
 
here is the starter code public class LinkedListPracticeLab.pdf
geetakannupillai1
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
footstatus
 
Chapter 4 Linked List introduction lessons.pptx
MohamedAhmed686097
 
practice of using and manipulating a doubly linked list and (2) prac.pdf
rd1742
 
Fix my codeCode.pdf
Conint29
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
deepakangel
 
You can list anything, it doesnt matter. I just want to see code f.pdf
fashionbigchennai
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
arrowmobile
 
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdf
aptind
 
Use the singly linked list class introduced in the lab to implement .pdf
sales87
 
Linked List Objective The purpose of this exercise is to cr.pdf
adityacomputers001
 
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
Stewart29UReesa
 
import java-util--- public class MyLinkedList{ public static void.pdf
asarudheen07
 
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
Komlin1
 
In this assignment you will implement insert() method for a singly l.pdf
fantasiatheoutofthef
 
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
fantasiatheoutofthef
 

More from kingsandqueens3 (20)

PDF
products apperar below Assume that sulficient time is available on the.pdf
kingsandqueens3
 
PDF
Procedure for Activity 1-2- Applying Directional Terms Part 1 Procedur.pdf
kingsandqueens3
 
PDF
process- and conversion costs are added everly during the peocess- Spo.pdf
kingsandqueens3
 
PDF
Process capability A- exists when CPK is less than 1-0- B- means that.pdf
kingsandqueens3
 
PDF
Problem VII - Debt and Stock Investments Cam Inc- has decided to inves.pdf
kingsandqueens3
 
PDF
Problem V-Fair Value Adiustment HQ Inc- has the following trading port.pdf
kingsandqueens3
 
PDF
Problem Statement Several students in our college struggle with academ.pdf
kingsandqueens3
 
PDF
Problem Gross Estate For each type of decedent- compute for the gross.pdf
kingsandqueens3
 
PDF
Problem IV - Stock Investments Mal- Inc- acquired 25- of the outstandi.pdf
kingsandqueens3
 
PDF
Problem E Let X be the number of heads in n flips of a coin with proba.pdf
kingsandqueens3
 
PDF
Problem C- Huntington's disease results from the presence of a dominan.pdf
kingsandqueens3
 
PDF
Problem B (5 points)- A medical sociologist investigated the relations.pdf
kingsandqueens3
 
PDF
Problem 9- (4 marks) Let symbol denote -exclusive or - that is pq(pq).pdf
kingsandqueens3
 
PDF
Problem 6 (4 marks) Matt and Sandeep are partners with capital balance.pdf
kingsandqueens3
 
PDF
Problem 6 The function -move- takes as input a list of numbers- Explai.pdf
kingsandqueens3
 
PDF
Problem 5- Assume 5 points are placed into an equilateral triangle of.pdf
kingsandqueens3
 
PDF
Problem 4- Show that in the recurrence T(n)-0qn1max(T(q)+T(nq1))+n- T(.pdf
kingsandqueens3
 
PDF
Problem 4 An analyst has a dataset of n-1-000 observations of (Yi-Xi)-.pdf
kingsandqueens3
 
PDF
Problem 4- Repeated Permutations a) In how many ways the letters of th.pdf
kingsandqueens3
 
PDF
Problem 4 Suppose that the returns to education is 13-4- per year for.pdf
kingsandqueens3
 
products apperar below Assume that sulficient time is available on the.pdf
kingsandqueens3
 
Procedure for Activity 1-2- Applying Directional Terms Part 1 Procedur.pdf
kingsandqueens3
 
process- and conversion costs are added everly during the peocess- Spo.pdf
kingsandqueens3
 
Process capability A- exists when CPK is less than 1-0- B- means that.pdf
kingsandqueens3
 
Problem VII - Debt and Stock Investments Cam Inc- has decided to inves.pdf
kingsandqueens3
 
Problem V-Fair Value Adiustment HQ Inc- has the following trading port.pdf
kingsandqueens3
 
Problem Statement Several students in our college struggle with academ.pdf
kingsandqueens3
 
Problem Gross Estate For each type of decedent- compute for the gross.pdf
kingsandqueens3
 
Problem IV - Stock Investments Mal- Inc- acquired 25- of the outstandi.pdf
kingsandqueens3
 
Problem E Let X be the number of heads in n flips of a coin with proba.pdf
kingsandqueens3
 
Problem C- Huntington's disease results from the presence of a dominan.pdf
kingsandqueens3
 
Problem B (5 points)- A medical sociologist investigated the relations.pdf
kingsandqueens3
 
Problem 9- (4 marks) Let symbol denote -exclusive or - that is pq(pq).pdf
kingsandqueens3
 
Problem 6 (4 marks) Matt and Sandeep are partners with capital balance.pdf
kingsandqueens3
 
Problem 6 The function -move- takes as input a list of numbers- Explai.pdf
kingsandqueens3
 
Problem 5- Assume 5 points are placed into an equilateral triangle of.pdf
kingsandqueens3
 
Problem 4- Show that in the recurrence T(n)-0qn1max(T(q)+T(nq1))+n- T(.pdf
kingsandqueens3
 
Problem 4 An analyst has a dataset of n-1-000 observations of (Yi-Xi)-.pdf
kingsandqueens3
 
Problem 4- Repeated Permutations a) In how many ways the letters of th.pdf
kingsandqueens3
 
Problem 4 Suppose that the returns to education is 13-4- per year for.pdf
kingsandqueens3
 
Ad

Recently uploaded (20)

PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Dimensions of Societal Planning in Commonism
StefanMz
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Ad

Problem- Describe an algorithm for concatenating two singly linked lis.pdf

  • 1. Problem: Describe an algorithm for concatenating two singly linked lists L and M, into a single list L that contains all the nodes of L followed by all the nodes of M. Modify the SinglyLinkedList class to contain the method: public void concatenate(SinglyLinkedList other) { ... } PLEASE PLEASE USE THE CODE BELOW..... THANK YOU public class SinglyLinkedList<E> implements Cloneable { //---------------- nested Node class ---------------- /** * Node of a singly linked list, which stores a reference to its * element and to the subsequent node in the list (or null if this * is the last node). */ private static class Node<E> { /** The element stored at this node */ private E element; // reference to the element stored at this node /** A reference to the subsequent node in the list */ private Node<E> 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 reference to a node that should follow the new node */ public Node(E e, Node<E> n) { element = e; next = n; } // Accessor methods /** * Returns the element stored at the node. * @return the element stored at the node */ public E getElement() { return element; } /** * Returns the node that follows this one (or null if no such node). * @return the following node */ public Node<E> getNext() { return next; }
  • 2. // Modifier methods /** * Sets the node's next reference to point to Node n. * @param n the node that should follow this one */ public void setNext(Node<E> n) { next = n; } } //----------- end of nested Node class ----------- // instance variables of the SinglyLinkedList /** The head node of the list */ private Node<E> head = null; // head node of the list (or null if empty) /** The last node of the list */ private Node<E> tail = null; // last node of the list (or null if empty) /** Number of nodes in the list */ private int size = 0; // number of nodes in the list /** Constructs an initially empty list. */ public SinglyLinkedList() { } // constructs an initially empty list // access 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() { // returns (but does not remove) the first element if (isEmpty()) return null; return head.getElement(); } /** * Returns (but does not remove) the last element of the list. * @return element at the end of the list (or null if empty)
  • 3. */ public E last() { // returns (but does not remove) the last element if (isEmpty()) return null; return tail.getElement(); } // update methods /** * Adds an element to the front of the list. * @param e the new element to add */ public void addFirst(E e) { // adds element e to the front of the list head = new Node<>(e, head); // create and link a new node if (size == 0) tail = head; // special case: new node becomes tail also size++; } /** * Adds an element to the end of the list. * @param e the new element to add */ public void addLast(E e) { // adds element e to the end of the list Node<E> newest = new Node<>(e, null); // node will eventually be the tail if (isEmpty()) head = newest; // special case: previously empty list else tail.setNext(newest); // new node after existing tail tail = newest; // new node becomes the tail size++; } /** * Removes and returns the first element of the list. * @return the removed element (or null if empty) */ public E removeFirst() { // removes and returns the first element if (isEmpty()) return null; // nothing to remove E answer = head.getElement(); head = head.getNext(); // will become null if list had only one node size--; if (size == 0) tail = null; // special case as list is now empty return answer; }
  • 4. @SuppressWarnings({"unchecked"}) public boolean equals(Object o) { if (o == null) return false; if (getClass() != o.getClass()) return false; SinglyLinkedList other = (SinglyLinkedList) o; // use nonparameterized type if (size != other.size) return false; Node walkA = head; // traverse the primary list Node walkB = other.head; // traverse the secondary list while (walkA != null) { if (!walkA.getElement().equals(walkB.getElement())) return false; //mismatch walkA = walkA.getNext(); walkB = walkB.getNext(); } return true; // if we reach this, everything matched successfully } @SuppressWarnings({"unchecked"}) public SinglyLinkedList<E> clone() throws CloneNotSupportedException { // always use inherited Object.clone() to create the initial copy SinglyLinkedList<E> other = (SinglyLinkedList<E>) super.clone(); // safe cast if (size > 0) { // we need independent chain of nodes other.head = new Node<>(head.getElement(), null); Node<E> walk = head.getNext(); // walk through remainder of original list Node<E> otherTail = other.head; // remember most recently created node while (walk != null) { // make a new node storing same element Node<E> newest = new Node<>(walk.getElement(), null); otherTail.setNext(newest); // link previous node to this one otherTail = newest; walk = walk.getNext(); } } return other; } public int hashCode() { int h = 0; for (Node walk=head; walk != null; walk = walk.getNext()) { h ^= walk.getElement().hashCode(); // bitwise exclusive-or with element's code h = (h << 5) | (h >>> 27); // 5-bit cyclic shift of composite code } return h; } /** * Produces a string representation of the contents of the list. * This exists for debugging purposes only.
  • 5. */ public String toString() { StringBuilder sb = new StringBuilder("("); Node<E> walk = head; while (walk != null) { sb.append(walk.getElement()); if (walk != tail) sb.append(", "); walk = walk.getNext(); } sb.append(")"); return sb.toString(); } public void concatenate(SinglyLinkedList<E> other) { ............. TYPE CODE HERE......... } } }