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;
}
}
s.substring(0)is same ass. I think you should be usings.charAt(0)instead. - user2030471nextofnodeto a new instance ofListNode? - Vivin Paliath.startsWithinstead of what you're doing. What you're currently doing returns the entire string. - Vivin Paliath