0
votes

I have a string called input which looks like: i52 i22 i36 i48 i32 d52 d32

The i in front of each number, represents an insert, and the d a delete.

Each individual number needs to be inserted into a LinkedList as a node if it is an insert a the end of the LinkedList. Or deleted from the LinkedList if it is a delete. For a delete, it should remove the node for the number equal to d##.

My current code:

LinkedList<ListNode> list = new LinkedList<ListNode>();
ListNode header = new ListNode(null);

    for (String s: input.split(" ")){

        if (s.charAt(0) == 'i') {
            ListNode node = new ListNode(s);
            node.next = new ListNode(s);
            list.add(node);
        }
        else if (s.charAt(0) == 'd'){
            list.remove(s);
        }
    }

I know my code is messed up in the insert and the delete loop. How do you create a new Node, and connect it to the next Node?


The node class is:

class ListNode
{
    Object   element;
    ListNode next;

    ListNode(Object theElement ) {
        this(theElement, null );
    }

    ListNode(Object theElement, ListNode n ) {
        element = theElement;
        next    = n;
    }
}
2
s.substring(0) is same as s. I think you should be using s.charAt(0) instead. - user2030471
Why are you assigning the next of node to a new instance of ListNode? - Vivin Paliath
Use .startsWith instead of what you're doing. What you're currently doing returns the entire string. - Vivin Paliath
Edited my code to use s.charAt(0), could you help a bit with the node insertion? - Paolo Bernasconi

2 Answers

1
votes

If you're using Java's LinkedList, all you have to do is:

if (s.charAt(0) == 'i') {
    ListNode node = new ListNode(s);
    list.add(node);
}

The LinkedList will take care of connecting nodes and 'linking' everything .

If you are making your own LinkedList, you have to define the add method in there. For example:

class LinkedList{
    ListNode head, tail;

    public void add(Object o){
        //Your add implementation
    }

    // ... other methods    
}
1
votes

Your approach seems to be redundant. Collection framework's LinkedList<T> will provide to link all the the elements ListNode you put in there. There is no need to use nodes with next field, unless you are trying to do something more.

Then your code doesn't insert the number xy for a ixy but the whole string. This can help:

LinkedList<String> list = new LinkedList<String>();

 for (String s: input.split(" ")){
     if(s.startsWith("i")){
         list.add(s.substring(1));
     }
     else if (s.charAt(0) == 'd'){
         list.remove(s.substring(1));
     }
 }