9. On the last page of these review problems is an implementation o the IntNode
ID: 3600473 • Letter: 9
Question
9. On the last page of these review problems is an implementation o the IntNode class. (a) Write an implementation of the static method public static int countZeros( IntNode node ) that will count the number of zeros that occur in the given linked list of ints. (b) Write an implementation of a static method public static String list2String( IntNode node) that returns a String representation of the linked list referred to by the parameter node. If the linked list is empty, the String representation should be " (two square brackets next to each other). If the linked list is not empty, the String representation should look like this, "3 52 0 2-4 16 1", with a space before and after each entry of the list. (c) Write a method public static IntNode removeFirst( IntNode head) that returns a reference to the second node from the linked list referred to by the parameter head. (d) Write a method public static IntNode addFirat( int element, IntNode head) that returns a reference to the new head of a linked list with a node containing element followed by the list referred to by the parameter head. (e) Write a method public static void set ( int element, int i, IntNode head) that modifies the list referred to by the parameter head so that the i'th node in the list has its data changed to element. If there is no i'th node in the list, then the list is not modified.Explanation / Answer
public static int countZeros(IntNode node){
int count = 0;
IntNode cur;
cur = node;
while (cur != NULL){
if (cur.data == 0)
count++;
}
return count;
}
public static String list2String(IntNode node){
int count = 0;
IntNode cur;
cur = node;
String res = "[";
while (cur != NULL){
res = res + " " + Integer.toString(cur.data);
}
res = res + "]";
return res;
}
public static IntNode removeFirst(IntNode head){
IntNode cur;
cur = head.next;
head = head.next;
return cur;
}
public static IntNode addFirst(int element IntNode head){
IntNode temp = new IntNode();
temp.data = element;
temp.next = head;
head = temp
return head;
}
public static void set(int element ,int i,IntNode head){
int count = 0;
IntNode cur;
cur = head;
while (cur != NULL && count != i){
cur = cur.next;
count++
}
if (cur == NULL)
System.out.println("Index exceeded the list length ");
else {
cur.data = element;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.