/** * Question 3: * * Complete the \"isEmpty()\" method below. * This method wil
ID: 3691471 • Letter: #
Question
/**
* Question 3:
*
* Complete the "isEmpty()" method below.
* This method will return true if the list is empty, otherwise it
* will return false.
*
* In other words, this method will return true if the head node
* is null, and false otherwise.
*
* Only add code in between the comments that say
* "Begin your code here"
* and
* "End your code here"
*/
public class LinkedList03 {
// Private inner class Node
private class Node{
int data;
Node link;
@SuppressWarnings("unused")
public Node(){
data = Integer.MIN_VALUE;
link = null;
}
public Node(int x, Node p){
data = x;
link = p;
}
}
// End of Node class
public Node head;
public LinkedList03(boolean initWithData) {
if (initWithData) {
head = new Node(5, null);
} else {
head = null;
}
}
public boolean isEmpty() {
/** Begin your code here **/
if(head==null)
return true;
else
return false;
/** end your code here **/
}
public void printList(){
Node position = head;
if (head == null)
System.out.println("The list is empty.");
while(position != null){
System.out.print(position.data + " ");
position = position.link;
}
}
public static void main(String[] args) {
LinkedList03 list = new LinkedList03(false);
System.out.println(list.isEmpty());
list = new LinkedList03(true);
System.out.println(list.isEmpty());
}
}
Explanation / Answer
Yes, your implementation is right.
public class LinkedList03 {
// Private inner class Node
private class Node{
int data;
Node link;
@SuppressWarnings("unused")
public Node(){
data = Integer.MIN_VALUE;
link = null;
}
public Node(int x, Node p){
data = x;
link = p;
}
}
// End of Node class
public Node head;
public LinkedList03(boolean initWithData) {
if (initWithData) {
head = new Node(5, null);
} else {
head = null;
}
}
public boolean isEmpty() {
/** Begin your code here **/
if(head==null)
return true;
else
return false;
/** end your code here **/
}
public void printList(){
Node position = head;
if (head == null)
System.out.println("The list is empty.");
while(position != null){
System.out.print(position.data + " ");
position = position.link;
}
}
public static void main(String[] args) {
LinkedList03 list = new LinkedList03(false);
System.out.println(list.isEmpty());
list = new LinkedList03(true);
System.out.println(list.isEmpty());
}
}
/*
Sample run:
true
false
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.