Click here to Skip to main content
14,734,526 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to retain all deteled nodes and restore the list in same state as it was before ?

What I have tried:

I have tried using stack to store all deleted items while deleting but dont know is it right approach or not.

public static String josephus(int m) {
Node ptr1 = start, ptr2 = start;
if (m > size) {
throw new LinkedListException("No element left to remove");
}

while (ptr1.next != ptr1) {

// Find m-th node
int count = 1;
while (count != m) {
ptr2 = ptr1;
ptr1 = ptr1.next;
count++;
}

/* Remove the m-th node */
System.out.println("Removing item : " + ptr1.data);
stack.push(ptr1.data);
ptr2.next = ptr1.next;
ptr1 = ptr2.next;
}

return ptr1.data;
}

public static void setOriginal(int m) {
Node ptr1 = start;
while (!stack.isEmpty() && ptr1.next != ptr1) {

// Find m-th node
int count = 1;
while (count != m) {
ptr1 = ptr1.next;
count++;
}

ptr1.data = stack.pop();
//System.out.println(ptr1.item);
}
}
Posted
Updated 12-Nov-20 0:37am
v2

1 solution

Quote:
I have tried using stack to store all deleted items while deleting but dont know is it right approach or not
You can experimentally establish that: check your results against the original list.

(Or post here your code, otherwise the question makes poor sense).
   
Comments
Aarsh Modi 12-Nov-20 5:28am
   
public static String josephus(int m) {
Node ptr1 = start, ptr2 = start;
if (m > size) {
throw new LinkedListException("No element left to remove");
}

while (ptr1.next != ptr1) {

// Find m-th node
int count = 1;
while (count != m) {
ptr2 = ptr1;
ptr1 = ptr1.next;
count++;
}

/* Remove the m-th node */
System.out.println("Removing item : " + ptr1.data);
stack.push(ptr1.data);
ptr2.next = ptr1.next;
ptr1 = ptr2.next;
}

return ptr1.data;
}

public static void setOriginal(int m) {
Node ptr1 = start;
while (!stack.isEmpty() && ptr1.next != ptr1) {

// Find m-th node
int count = 1;
while (count != m) {
ptr1 = ptr1.next;
count++;
}

ptr1.data = stack.pop();
//System.out.println(ptr1.item);
}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900