Skip to content
Advertisement

Make a moving cursor using doubly linked list in java

I’m trying to write a code for a simple moving cursor in java. I have to use doubly linked list. Also I should implement doubyLinkedList class myself. In this program first we take an integer like n from user as number of lines. Then we take n lines of input. Each line contains only one character which can be < or > or - or one of the lower case English alphabet. For > or < we move the cursor to right or left. For - we delete the character in the place of cursor. For alphabets we add them to the doubly linked list. At last we print the result in one line without spaces. I have made the doubyLinkedList class and needed methods. I think it is working properly but the time complexity of the code must be O(n). I guess it’s O(n^2) now.

JavaScript

How can I improve my code to reduce time complexity?

Edit: Also I understood that my code is giving wrong answer for some cases. Could you help me debug it?

Advertisement

Answer

If you are not forced to follow implementation details, I suggest not to have a cursor. Instead, keep a variable currentNode which is the node that the cursor would point to. So for every command (or data) in the input loop, you have one O(1) operation as bellow and hence will get O(n) time complexity.

1 – for > : change the currentNode to currentNode.next

2 – for < do the reverse

3 – for - change the previous and the next node of currentNode to point to each other (so the current is deleted)

4 – and finally for insertion : create a node and like 3, change the the side nodes to point to it

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement