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) { ... }
---------------Below is the code--------------------
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();
}
// Please Type your code here. Thank you.
// public void concatenate(SinglyLinkedList other) { ... }
}
}

More Related Content

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

PDF
210 Linked-llists of data structure with .pdf
AhsanRamzan7
 
PDF
Add these methods to the code - -Create at least three classes such.pdf
SebastianRzuHarrisw
 
PDF
STAGE 2 The Methods 65 points Implement all the methods t.pdf
babitasingh698417
 
PDF
package linkedLists- import java-util-Iterator- --- A class representi.pdf
arcellzone
 
PDF
Fix my codeCode.pdf
Conint29
 
PDF
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
deepakangel
 
PDF
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
footstatus
 
PDF
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
arrowmobile
 
PDF
practice of using and manipulating a doubly linked list and (2) prac.pdf
rd1742
 
PDF
here is the starter code public class LinkedListPracticeLab.pdf
geetakannupillai1
 
PDF
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
Stewart29UReesa
 
PDF
Hi,I have added the methods and main class as per your requirement.pdf
annaelctronics
 
PDF
import java-util--- public class MyLinkedList{ public static void.pdf
asarudheen07
 
PDF
Note             Given Code modified as required and required met.pdf
Ankitchhabra28
 
PDF
Use the singly linked list class introduced in the lab to implement .pdf
sales87
 
DOCX
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
Komlin1
 
PDF
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdf
aptind
 
PDF
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
xlynettalampleyxc
 
PDF
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
fantasiatheoutofthef
 
PDF
You can list anything, it doesnt matter. I just want to see code f.pdf
fashionbigchennai
 
210 Linked-llists of data structure with .pdf
AhsanRamzan7
 
Add these methods to the code - -Create at least three classes such.pdf
SebastianRzuHarrisw
 
STAGE 2 The Methods 65 points Implement all the methods t.pdf
babitasingh698417
 
package linkedLists- import java-util-Iterator- --- A class representi.pdf
arcellzone
 
Fix my codeCode.pdf
Conint29
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
deepakangel
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
footstatus
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
arrowmobile
 
practice of using and manipulating a doubly linked list and (2) prac.pdf
rd1742
 
here is the starter code public class LinkedListPracticeLab.pdf
geetakannupillai1
 
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
Stewart29UReesa
 
Hi,I have added the methods and main class as per your requirement.pdf
annaelctronics
 
import java-util--- public class MyLinkedList{ public static void.pdf
asarudheen07
 
Note             Given Code modified as required and required met.pdf
Ankitchhabra28
 
Use the singly linked list class introduced in the lab to implement .pdf
sales87
 
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
Komlin1
 
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdf
aptind
 
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
xlynettalampleyxc
 
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
fantasiatheoutofthef
 
You can list anything, it doesnt matter. I just want to see code f.pdf
fashionbigchennai
 

More from JamesPXNNewmanp (20)

PDF
Q1- Write an online -fact sheet- for the public on issues with privacy.pdf
JamesPXNNewmanp
 
PDF
Quality Improvement Organizations (QIOs) were created under the ______.pdf
JamesPXNNewmanp
 
PDF
Q9- Which networking device broadcasts data to all wired devices attac.pdf
JamesPXNNewmanp
 
PDF
QS 15-18 (Algo) Computing and recording over- or underapplied everhead.pdf
JamesPXNNewmanp
 
PDF
Q6) Code Generation Part 1) Write a code generator for the language co.pdf
JamesPXNNewmanp
 
PDF
Q3 (10 points)- Table below from the 2016 General Social Survey- has Y.pdf
JamesPXNNewmanp
 
PDF
q1Five (5) advantages of google maps- q2 Identify EIGHT (8) basic form.pdf
JamesPXNNewmanp
 
PDF
Q2- Betty types up a paper that states- -I recognize that I owe Cathy.pdf
JamesPXNNewmanp
 
PDF
Q1- Given is the symbol of a 1-bit full adder- Please draw a diagram t.pdf
JamesPXNNewmanp
 
PDF
PYTHON File Analysis Write a program that reads the contents of the tw.pdf
JamesPXNNewmanp
 
PDF
Python CMSC 206 Please fix this code- send me what I should enter- and.pdf
JamesPXNNewmanp
 
PDF
Psychiatrist from Munich who devised a classification of mental disord.pdf
JamesPXNNewmanp
 
PDF
provide project managers and their teams with access to informal organ.pdf
JamesPXNNewmanp
 
PDF
Pseudopods are used by amoebas for locomotion- A- True B- False QUESTI.pdf
JamesPXNNewmanp
 
PDF
Provide a substantive comnent to this post- Statistics in R is a pow.pdf
JamesPXNNewmanp
 
PDF
Project Pink initially costs Rs- 25-000- It generates the following ca.pdf
JamesPXNNewmanp
 
PDF
proinsulin What triggers the closure of KATP channels and the subseque.pdf
JamesPXNNewmanp
 
PDF
Producers and suppliers andtheir role in the housing stockshortage of.pdf
JamesPXNNewmanp
 
PDF
Problem 9- (10 points) The mean and standard deviation of a random var.pdf
JamesPXNNewmanp
 
PDF
Problem 7-20.pdf
JamesPXNNewmanp
 
Q1- Write an online -fact sheet- for the public on issues with privacy.pdf
JamesPXNNewmanp
 
Quality Improvement Organizations (QIOs) were created under the ______.pdf
JamesPXNNewmanp
 
Q9- Which networking device broadcasts data to all wired devices attac.pdf
JamesPXNNewmanp
 
QS 15-18 (Algo) Computing and recording over- or underapplied everhead.pdf
JamesPXNNewmanp
 
Q6) Code Generation Part 1) Write a code generator for the language co.pdf
JamesPXNNewmanp
 
Q3 (10 points)- Table below from the 2016 General Social Survey- has Y.pdf
JamesPXNNewmanp
 
q1Five (5) advantages of google maps- q2 Identify EIGHT (8) basic form.pdf
JamesPXNNewmanp
 
Q2- Betty types up a paper that states- -I recognize that I owe Cathy.pdf
JamesPXNNewmanp
 
Q1- Given is the symbol of a 1-bit full adder- Please draw a diagram t.pdf
JamesPXNNewmanp
 
PYTHON File Analysis Write a program that reads the contents of the tw.pdf
JamesPXNNewmanp
 
Python CMSC 206 Please fix this code- send me what I should enter- and.pdf
JamesPXNNewmanp
 
Psychiatrist from Munich who devised a classification of mental disord.pdf
JamesPXNNewmanp
 
provide project managers and their teams with access to informal organ.pdf
JamesPXNNewmanp
 
Pseudopods are used by amoebas for locomotion- A- True B- False QUESTI.pdf
JamesPXNNewmanp
 
Provide a substantive comnent to this post- Statistics in R is a pow.pdf
JamesPXNNewmanp
 
Project Pink initially costs Rs- 25-000- It generates the following ca.pdf
JamesPXNNewmanp
 
proinsulin What triggers the closure of KATP channels and the subseque.pdf
JamesPXNNewmanp
 
Producers and suppliers andtheir role in the housing stockshortage of.pdf
JamesPXNNewmanp
 
Problem 9- (10 points) The mean and standard deviation of a random var.pdf
JamesPXNNewmanp
 
Problem 7-20.pdf
JamesPXNNewmanp
 
Ad

Recently uploaded (20)

PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
community health nursing question paper 2.pdf
Prince kumar
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
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) { ... } ---------------Below is the code-------------------- 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
  • 2. */ 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(); }
  • 3. /** * 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
  • 4. 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; }
  • 5. /** * 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(); } // Please Type your code here. Thank you. // public void concatenate(SinglyLinkedList other) { ... } } }