Click here to Skip to main content
15,919,341 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am working on dataStructures and Algorithms.
I am currently working on linklist and stack.

In linklist i have created the delete method, which is going to remove the node from the linklist but i want to store the deleted node into a stack and then undo the store node in the stack back in the list and display it.
I need the assistance in order to solve the problem at hand.

What I have tried:

    public int delete(int index){
        if(index == 0){
            return deleteFirst();
        }
        if(index == size - 1){
            return deleteLast();
        }
        Node prev = get(index - 1);

        int val = prev.next.value;

        prev.next = prev.next.next;

//        mystack.push(val);

        return val;
    }
Posted
Updated 21-May-24 23:46pm
v2
Comments
Richard Deeming 22-May-24 5:52am    
You haven't explained what assistance you need.

The only obvious issue that jumps out is that if the linked list is not sorted, storing the value you've removed won't be enough to restore it in the correct position; you'll also need to store the index you removed it from.

I wouldn't have called the mystack.push(val); inside the delete method of the list.
Instead I would have written (in the 'consumer' code) something like
Java
int val = mylist.delete(index);
mystack.push(val);
 
Share this answer
 
Comments
samcodeonline 22-May-24 8:20am    
I want to store this deleted node in a stack and then displaying it again in the list i deleted it from. Could you provide me with the code, that i want to accomplish.
Dave Kreskowiak 22-May-24 10:15am    
Nobody is going to write your code for you. The only code you get is the code YOU write.
samcodeonline 22-May-24 8:20am    
custom linklist and stack implementation
Like Richard said, you cannot restore the node you pushed onto the stack because you're losing the position in the linked list where the node came from.

To make this work, you would have to create a class that can hold your node instance AND the data required to insert it back into the correct position in the linked list. When you delete a node from the list, you create an instance of this wrapper object, populate it with the node you're deleting and the position information, and push this wrapper object onto the stack.
 
Share this answer
 

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