public class Main {
// Node class remains the same
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// 1. Declare head and tail as member variables for the list
Node head;
Node tail;
int size = 0; // Keep track of the size
// 2. Implement the 'add' methods for your custom list
public void addFirst(int data) {
Node newNode = new Node(data);
size++;
if (head == null) {
head = tail = newNode;
return;
}
newNode.next = head;
head = newNode;
}
public void addLast(int data) {
Node newNode = new Node(data);
size++;
if (head == null) {
head = tail = newNode;
return;
}
tail.next = newNode;
tail = newNode;
}
public void add(int index, int data) {
if (index < 0 || index > size) {
System.out.println("Invalid index");
return;
}
if (index == 0) {
addFirst(data);
return;
}
Node temp = head;
for (int i = 0; i < index - 1; i++) {
temp = temp.next;
}
Node newNode = new Node(data);
newNode.next = temp.next;
temp.next = newNode;
size++;
}
public void deleteNthfromEnd(int n) {
// calculate size
int size = 0;
Node temp = head;
while(temp != null) {
temp = temp.next;
size++;
}
if(n == size) {
head = head.next; // removeFirst
return;
}
// size-n
int i = 1;
int iToFind = size-n;
Node prev = head;
while(i < iToFind) {
prev = prev.next;
i++;
}
prev.next = prev.next.next;
return;
}
// Your reverse method is correct for this custom implementation
public void reverse() {
Node prev = null;
Node curr = tail = head; // The old head becomes the new tail
Node next;
while (curr != null) {
next = curr.next; // Store the next node
curr.next = prev; // Reverse the current node's pointer
prev = curr; // Move pointers one position ahead
curr = next; // Move pointers one position ahead
}
head = prev; // The last node visited (prev) is the new head
}
// Your printList method is correct for this custom implementation
public void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("null");
}
public static void main(String[] args) {
// 3. Instantiate your custom Main class, not java.util.LinkedList
Main ll = new Main();
// The list will be: 2 -> 2 -> 4 -> 5
ll.addFirst(2);
ll.addFirst(1);
ll.addLast(4);
ll.addLast(5);
// After this, the list is: 2 -> 2 -> 3 -> 4 -> 5
ll.add(2, 3);
System.out.println("Original List:");
ll.printList();
ll.deleteNthfromEnd(3);
ll.printList();
}
}
No comments:
Post a Comment