SlideShare a Scribd company logo
1 of 8
Download to read offline
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

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

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

Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
Given below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfGiven below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdf
 
package linkedLists- import java-util-Iterator- --- A class representi.pdf
package linkedLists- import java-util-Iterator- --- A class representi.pdfpackage linkedLists- import java-util-Iterator- --- A class representi.pdf
package linkedLists- import java-util-Iterator- --- A class representi.pdf
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
 
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdfLabProgram.javaimport java.util.NoSuchElementException;public .pdf
LabProgram.javaimport java.util.NoSuchElementException;public .pdf
 
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjhlinked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
linked List.docx vhjgvjhvgjhjhbbjkhkjhkjh
 
please i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfplease i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdf
 
Note- Can someone help me with the Public boolean add(E value) method.pdf
Note- Can someone help me with the Public boolean add(E value) method.pdfNote- Can someone help me with the Public boolean add(E value) method.pdf
Note- Can someone help me with the Public boolean add(E value) method.pdf
 
Please complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docxPlease complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docx
 
Program to insert in a sorted list #includestdio.h#include.pdf
 Program to insert in a sorted list #includestdio.h#include.pdf Program to insert in a sorted list #includestdio.h#include.pdf
Program to insert in a sorted list #includestdio.h#include.pdf
 
Note- Can someone help me with the private E get(int index- int curren (1).docx
Note- Can someone help me with the private E get(int index- int curren (1).docxNote- Can someone help me with the private E get(int index- int curren (1).docx
Note- Can someone help me with the private E get(int index- int curren (1).docx
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
 
here is the starter code public class LinkedListPracticeLab.pdf
here is the starter code public class LinkedListPracticeLab.pdfhere is the starter code public class LinkedListPracticeLab.pdf
here is the starter code public class LinkedListPracticeLab.pdf
 
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
--INSTRUCTION- --It helps to first create if-then-else structure to fi.pdf
 
Jhtp5 20 Datastructures
Jhtp5 20 DatastructuresJhtp5 20 Datastructures
Jhtp5 20 Datastructures
 
in Java (ignore the last line thats hidden) Create a doubly linked l.pdf
in Java (ignore the last line thats hidden) Create a doubly linked l.pdfin Java (ignore the last line thats hidden) Create a doubly linked l.pdf
in Java (ignore the last line thats hidden) Create a doubly linked l.pdf
 
How do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdfHow do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdf
 
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdfNeed Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
Need Help!! C++ #include-iostream- #include-linkedlist-h- using namesp.pdf
 

More from deepak596396

Derive the Hicksian demand functions for goods 1 and 2 using Envelope.pdf
Derive the Hicksian demand functions for goods 1 and 2 using Envelope.pdfDerive the Hicksian demand functions for goods 1 and 2 using Envelope.pdf
Derive the Hicksian demand functions for goods 1 and 2 using Envelope.pdf
deepak596396
 
Demonstrate your knowiedfe- Refer to the text and figures as netiod- t.pdf
Demonstrate your knowiedfe- Refer to the text and figures as netiod- t.pdfDemonstrate your knowiedfe- Refer to the text and figures as netiod- t.pdf
Demonstrate your knowiedfe- Refer to the text and figures as netiod- t.pdf
deepak596396
 
Exercise- You will use the TCP echo client and server code (for IPv4 v.pdf
Exercise- You will use the TCP echo client and server code (for IPv4 v.pdfExercise- You will use the TCP echo client and server code (for IPv4 v.pdf
Exercise- You will use the TCP echo client and server code (for IPv4 v.pdf
deepak596396
 

More from deepak596396 (20)

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

Recently uploaded

會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
中 央社
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 

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){ ..... } }