Create a LinkedList for the following node: class Node { public String name; pub
ID: 3577743 • Letter: C
Question
Create a LinkedList for the following node:
class Node {
public String name;
public Node next;
Node( ) { }
Node(Sting s) { // set the name }
}
Implement code for all methods for the LinkedList and create a main program to test each method in the LinkedList.
class MyLinkedList {
private Node head;
MyLinkedList( ) { }
public void addNode(Node n) { // add a Node to end of the LinkedList }
public void printList( ) { // print each element in the LinkedList }
public void insertBefore (int index, Node n) { // adds Node n before index value }
public void insertAfter (int index, Node n) { // adds Node n after index value }
public int indexOf (String str) { //returns index of where String str is at. Returns -1 if String str
is not in LinkedList }
public void removeNodeAt(int index) { // removes Node at index value }
}
Explanation / Answer
public class MyLinkedList{
private Node head;
public MyLinkedList(){
this.head = null;
}
public void addNode(Node n){
if (head==null){
head = n;
}
else{
Node curr = this.head;
while (curr.next!=null){
curr = curr.next;
}
curr.next = n;
}
}
public void printList(){
Node curr = head;
while(curr!=null){
System.out.print(curr.name+" -> ");
curr = curr.next;
}
System.out.println("");
}
public void insertBefore(int index, Node n){
Node curr = head;
int i = 0;
while(i<index-1){
if(curr.next==null){
System.out.println("Can't insert there.");
return;
}
curr = curr.next;
i++;
}
Node next = curr.next;
curr.next = n;
n.next = next;
}
public void insertAfter(int index, Node n){
Node curr = head;
int i = 0;
while(i<index){
if(curr==null){
System.out.println("Can't insert there.");
return;
}
curr = curr.next;
i++;
}
Node next = curr.next;
curr.next = n;
n.next = next;
}
public int indexOf(String str){
Node curr = head;
int i = 0;
while(curr.name!=str){
if (curr.next==null){
System.out.println("Not found");
return -1;
}
i++;
curr = curr.next;
}
return i;
}
public void removeNode(int index){
Node curr = head;
int i = 0;
while(i<index-1){
if (curr.next==null){
System.out.println("Not found");
return;
}
i++;
curr = curr.next;
}
Node next = curr.next.next;
curr.next = next;
}
public static void main(String[] args) {
MyLinkedList ll = new MyLinkedList();
ll.addNode(new Node("first"));
ll.addNode(new Node("second"));
ll.addNode(new Node("third"));
ll.addNode(new Node("fourth"));
ll.addNode(new Node("fifth"));
ll.printList();
ll.indexOf("third");
ll.removeNode(2);
ll.printList();
}
}
class Node{
public String name;
public Node next;
Node(){
this.name = "";
this.next = null;
}
Node(String s){
this.name = s;
this.next = null;
}
}