SlideShare a Scribd company logo
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
SinglyLinkedList which need to add public void concatenation(SinglyLinkedList other){}
at the end of the sample 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();
}
public void concatenation(SinglyLinkedList other){
.....
}
}

More Related Content

Similar to Describe an algorithm for concatenating two singly linked lists L and.pdf (20)

PDF
Data Structures in C++I am really new to C++, so links are really .pdf
rohit219406
 
PDF
Given below is the completed implementation of MyLinkedList class. O.pdf
info430661
 
PDF
package linkedLists- import java-util-Iterator- --- A class representi.pdf
arcellzone
 
PDF
Hi,I have added the methods and main class as per your requirement.pdf
annaelctronics
 
PDF
File LinkedList.java Defines a doubly-l.pdf
Conint29
 
PDF
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
climatecontrolsv
 
PDF
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
fantasiatheoutofthef
 
DOCX
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
vasavim9
 
PDF
please i need help Im writing a program to test the merge sort alg.pdf
ezonesolutions
 
PDF
Note- Can someone help me with the Public boolean add(E value) method.pdf
Stewart29UReesa
 
DOCX
Please complete all the code as per instructions in Java programming.docx
cgraciela1
 
PDF
Program to insert in a sorted list #includestdio.h#include.pdf
sudhirchourasia86
 
DOCX
Note- Can someone help me with the private E get(int index- int curren (1).docx
VictorzH8Bondx
 
PDF
This assignment and the next (#5) involve design and development of a.pdf
EricvtJFraserr
 
PDF
here is the starter code public class LinkedListPracticeLab.pdf
geetakannupillai1
 
PDF
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
AdrianEBJKingr
 
PPT
Jhtp5 20 Datastructures
martha leon
 
PDF
in Java (ignore the last line thats hidden) Create a doubly linked l.pdf
sauravmanwanicp
 
PDF
How do I fix it in javaLinkedList.java Defines a doubl.pdf
fmac5
 
PDF
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
Edwardw5nSlaterl
 
Data Structures in C++I am really new to C++, so links are really .pdf
rohit219406
 
Given below is the completed implementation of MyLinkedList class. O.pdf
info430661
 
package linkedLists- import java-util-Iterator- --- A class representi.pdf
arcellzone
 
Hi,I have added the methods and main class as per your requirement.pdf
annaelctronics
 
File LinkedList.java Defines a doubly-l.pdf
Conint29
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
climatecontrolsv
 
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
fantasiatheoutofthef
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
vasavim9
 
please i need help Im writing a program to test the merge sort alg.pdf
ezonesolutions
 
Note- Can someone help me with the Public boolean add(E value) method.pdf
Stewart29UReesa
 
Please complete all the code as per instructions in Java programming.docx
cgraciela1
 
Program to insert in a sorted list #includestdio.h#include.pdf
sudhirchourasia86
 
Note- Can someone help me with the private E get(int index- int curren (1).docx
VictorzH8Bondx
 
This assignment and the next (#5) involve design and development of a.pdf
EricvtJFraserr
 
here is the starter code public class LinkedListPracticeLab.pdf
geetakannupillai1
 
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
AdrianEBJKingr
 
Jhtp5 20 Datastructures
martha leon
 
in Java (ignore the last line thats hidden) Create a doubly linked l.pdf
sauravmanwanicp
 
How do I fix it in javaLinkedList.java Defines a doubl.pdf
fmac5
 
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
Edwardw5nSlaterl
 

More from deepak596396 (20)

PDF
Describe how the bioavailability of calcium varies and then identify s.pdf
deepak596396
 
PDF
Describe communication choices at each stage of the speech creation pr.pdf
deepak596396
 
PDF
Deion- a very-task oriented leader- has recently taken on a management.pdf
deepak596396
 
PDF
Derive the Hicksian demand functions for goods 1 and 2 using Envelope.pdf
deepak596396
 
PDF
D- Maintaining History The final milestone of the project is to build.pdf
deepak596396
 
PDF
deram pacios) Ths 05- coridecocai inteivel bored vooa n-100 is decima.pdf
deepak596396
 
PDF
Demonstrate your knowiedfe- Refer to the text and figures as netiod- t.pdf
deepak596396
 
PDF
D- Classifying Acids and Bases The pH of a solution is a number which.pdf
deepak596396
 
PDF
Deliverable- Create two single user empathy maps- as described below-.pdf
deepak596396
 
PDF
d- By how much does the supply of money supply or contract- Supply of.pdf
deepak596396
 
PDF
Define the following terms- and explain it in your own words with exam.pdf
deepak596396
 
PDF
Deinococcus radiodurans is a bacteria with a very peculiar special abi.pdf
deepak596396
 
PDF
Define a method printFeetinchShort- with int parameters numFeet and nu.pdf
deepak596396
 
PDF
Define a method named orderOfAppearance() that takes the name of a rol.pdf
deepak596396
 
PDF
D) there is little change across horizontal distances- Question 14 (Ma.pdf
deepak596396
 
PDF
Define a method findResources() that takes two integer parameters as a.pdf
deepak596396
 
PDF
Exhibit 11-7 We want to test the hypothesis that population B has a.pdf
deepak596396
 
PDF
Exercise- You will use the TCP echo client and server code (for IPv4 v.pdf
deepak596396
 
PDF
Exercise 8 1- Discuss the relevance of the Dutch disease problem for.pdf
deepak596396
 
PDF
EXERCISE 7 - Let (Xn)n1 be a sequence of random variables such that Xn.pdf
deepak596396
 
Describe how the bioavailability of calcium varies and then identify s.pdf
deepak596396
 
Describe communication choices at each stage of the speech creation pr.pdf
deepak596396
 
Deion- a very-task oriented leader- has recently taken on a management.pdf
deepak596396
 
Derive the Hicksian demand functions for goods 1 and 2 using Envelope.pdf
deepak596396
 
D- Maintaining History The final milestone of the project is to build.pdf
deepak596396
 
deram pacios) Ths 05- coridecocai inteivel bored vooa n-100 is decima.pdf
deepak596396
 
Demonstrate your knowiedfe- Refer to the text and figures as netiod- t.pdf
deepak596396
 
D- Classifying Acids and Bases The pH of a solution is a number which.pdf
deepak596396
 
Deliverable- Create two single user empathy maps- as described below-.pdf
deepak596396
 
d- By how much does the supply of money supply or contract- Supply of.pdf
deepak596396
 
Define the following terms- and explain it in your own words with exam.pdf
deepak596396
 
Deinococcus radiodurans is a bacteria with a very peculiar special abi.pdf
deepak596396
 
Define a method printFeetinchShort- with int parameters numFeet and nu.pdf
deepak596396
 
Define a method named orderOfAppearance() that takes the name of a rol.pdf
deepak596396
 
D) there is little change across horizontal distances- Question 14 (Ma.pdf
deepak596396
 
Define a method findResources() that takes two integer parameters as a.pdf
deepak596396
 
Exhibit 11-7 We want to test the hypothesis that population B has a.pdf
deepak596396
 
Exercise- You will use the TCP echo client and server code (for IPv4 v.pdf
deepak596396
 
Exercise 8 1- Discuss the relevance of the Dutch disease problem for.pdf
deepak596396
 
EXERCISE 7 - Let (Xn)n1 be a sequence of random variables such that Xn.pdf
deepak596396
 
Ad

Recently uploaded (20)

PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Ad

Describe an algorithm for concatenating two singly linked lists L and.pdf

  • 1. 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 SinglyLinkedList which need to add public void concatenation(SinglyLinkedList other){} at the end of the sample 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;
  • 2. 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)
  • 3. /** 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;
  • 4. 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.
  • 5. * @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;
  • 6. } @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
  • 7. 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() {
  • 8. 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 concatenation(SinglyLinkedList other){ ..... } }