In: Computer Science
public class SinglyLikedList {
private class Node{
public int item;
public Node next;
public Node(int item, Node next)
{
this.item =
item;
this.next =
next;
}
}
private Node first;
public void addFirst(int a) {
first = new Node(a, first);
}
}
1. Write the method add(int item, int position), which takes an item and a position, and adds a new item at the provided position. For example, suppose that SinglyLikedList is 5->10->3->15, add(22, 4), the resulting list should be 5->10->3->15->22.
2. Write the method reverseList() for the SinglyLikedList that returns the items in a reverse order. For example, given 5->10->3->15->22, the resulting list should be 22->15->3->10->5.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
Note: I have changed the class name from SinglyLikedList to SinglyLinkedList. You may use whichever name you want. But make sure to update it everywhere.
//SinglyLinkedList.java (name corrected)
public class SinglyLinkedList {
private class Node {
public int item;
public Node next;
public Node(int item, Node next) {
this.item = item;
this.next = next;
}
}
private Node first;
public void addFirst(int a) {
first = new Node(a, first);
}
// method to add item to index=position
public void add(int item, int position) {
// if position is negative, exiting method
if (position < 0) {
return;
}
// if posi8tion is 0, adding new node before current first
if (position == 0) {
first = new Node(item, first);
return;
}
// else taking a reference to first
Node temp = first;
// advancing it position-1 times. or until temp is null, whichever comes
// first
for (int i = 0; i < position - 1 && temp != null; i++) {
temp = temp.next;
}
// if temp is null, that means position is invalid, in which case we
// simply exit the method
if (temp == null) {
return;
}
// else adding new node between temp and temp.next
temp.next = new Node(item, temp.next);
}
// method to return a reversed list
public SinglyLinkedList reverseList() {
// creating a SinglyLinkedList
SinglyLinkedList result = new SinglyLinkedList();
// looping through each node in this list
for (Node n = first; n != null; n = n.next) {
// adding data of this node before the current first element of the
// result list
result.first = new Node(n.item, result.first);
}
// returning reversed list
return result;
}
}