complete the methods listed below for class LinkedListHT. In each case the comment inserted in the method
Question:
complete the methods listed below for class LinkedListHT. In each case the comment
inserted in the method describes its purpose.
import java.util.*;
public class Assignment {
public static void main(String[] args) {
//Test code here=========================================
//======================================================
}
}
class LinkedListHT{
private Node head = null; private Node tail = null;
//empty list
public void addTail(int x){ //add at head
Node nw = new Node(x);
if(head == null){
head = nw; tail = nw;
}
else{
tail.setNext(nw);
tail = nw;
}
}
public void addHead(int x){
//insert x at head of list
Node nw = new Node(x);
if(head == null){
head = nw; tail = nw;
}
else{
nw.setNext(head);
head = nw;
}
}
public void delTail(){
if(head == tail){
head = null; tail = null;
}
else{
Node k = head;
while(k.next() != tail) k = k.next();
k.setNext(null);
tail = k;
}
}
/*
public int size(){
//return number of nodes in the list
}
public void delHead(){
//remove element at head of list
}
public void delAll(int x){
//delete all occurrences of x from the list
}
public int sum(){
//calculate sum of values in the list
}
public int sumEven(){
//calculate sum of even values in the list
}
public int count(int x){
//count number of occurrences of x in list
}
public void addTail(LinkedListHT lst){
//add given list to tail of existing list
}
public int[] toArray(){
//return int array of list values
}
public void reverse(){
//reverse the order of the lements in the list
}
public boolean equals(Object ob){
// method to test this list with another list for equality
// Two lists equal if they have the same size and corresponding
// values are equal
}
*/
public boolean contains(int x){
Node k = head;
boolean found = false;
while(k != null && !found){
if(k.data() == x) found = true;
else k = k.next();
}
return found;
}
public void remove(int x){
Node k = head; Node bk = head;
boolean found = false;
while(k != null && !found){
if(k.data() == x) found = true;
else{ bk = k; k = k.next();}
}
if(found){
if(k == head)
head = k.next();
else if(k == tail){
bk.setNext(null);
tail = bk;
}
else
bk.setNext(k.next());
}
}
public String toString(){
if(head == null) return "[]";
String s = "[";
Node k = head;
while(k.next() != null){
s = s + k.data()+", ";
k = k.next();
}
s = s + k.data()+"]";
return s;
}
private class Node{
int data;
Node next;
public Node(int x){
data = x; next = null;
}
public Node next(){return next;}
public void setNext(Node p){
next = p;
}
public void set(int x){data = x;}
public int data(){return data;}
}
}
Java How To Program Late Objects Version
ISBN: 9780136123712
8th Edition
Authors: Paul Deitel, Deitel & Associates