Problem 1 The following Java implementation of a class Node
Problem #1: The following Java implementation of a class Node is given:
private class Node<Object>
{
Node() { this(null, null);
}
Node(Object d)
{
this(d, null);
}
Node(Object d, Node n)
{
data = d;
next = n;
}
Object data;
Node next;
}
Assume that a singly linked list is implemented with a header node, but no tail node, and that it maintains only a reference to the header node. Using the class Node described above, write a MySingleLinkedList class in Java includes methods to:
(a)
int size()
- return the size of the linked list.
(b)
void print()
- print the linked list.
(c)
boolean contains(Object x)
- test if a value x is contained in the linked list.
(d)
boolean add(Object x)
- add a value x if it is not already contained in thelinked list.
(e)
boolean remove(Object x)
- remove a value x if it is contained in the linked list.
Solution
package mysinglelinkedlist;
public class MySingleLinkedList<Object> {
private Node<Object> head;
/* a.) return the size of the linked list. */
public int size(){
int length=0;
Node<Object> tmp = head;
while(true){
if(tmp == null){
break;
}
length++;
tmp = tmp.next;
}
return length;
}
/* b.) print the linked list. */
public void print(){
Node<Object> tmp = head;
while(true){
if(tmp == null){
break;
}
System.out.println(tmp.data);
tmp = tmp.next;
}
}
/* c.) test if a value x is contained in the linked list.*/
public boolean contains(Object x){
Node<Object> tmp = head;
while(tmp!=null)
{
if(tmp.data!=x){
tmp = tmp.next;
}
else{
return true;
}
}
return false;
}
/* d.) add a value x if it is not already contained in thelinked list. */
public boolean add(Object element){
Node<Object> nd = new Node<Object>();
nd.data = element;
System.out.println(\"Adding: \"+element);
/**
* check if the list is empty
*/
if(head == null){
//since there is only one element, head
head = nd;
return true;
}
else {
boolean flag= contains(element);
if(flag==false){
head.next=nd;
return true;
}
else {
return false;
}
}
}
/* e.) remove a value x if it is contained in the linked list.*/
public boolean remove(Object x){
if(head == null){
System.out.println(\"Underflow...\");
return false;
}
Node<Object> tmp = head;
head = tmp.next;
if(head == null){
head.next = null;
}
System.out.println(\"Deleted: \"+tmp.data);
return true;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
MySingleLinkedList<Integer> sl = new MySingleLinkedList<Integer>();
sl.add(3);
sl.add(32);
sl.add(54);
sl.remove(32);
sl.print();
}
}
class Node<Object>
{
Node() { this(null, null);
}
Node(Object d)
{
this(d, null);
}
Node(Object d, Node n)
{
data = d;
next = n;
}
Object data;
Node next;
}




