在java中使用双链表创建移动光标
我正试图用java编写一个简单移动光标的代码。我必须使用双链表。我还应该自己实现doubyLinkedList类。在这个程序中,我们首先从用户那里获取一个整数,如在java中使用双链表创建移动光标,java,data-structures,time-complexity,doubly-linked-list,Java,Data Structures,Time Complexity,Doubly Linked List,我正试图用java编写一个简单移动光标的代码。我必须使用双链表。我还应该自己实现doubyLinkedList类。在这个程序中,我们首先从用户那里获取一个整数,如n,作为行数。然后我们取n行输入。每行仅包含一个字符,可以是或-或一个小写英文字母。对于或您不需要内部For循环。接受输入后立即处理输入 for (int i=0; i< n; i++) arr[i] = sc.nextLine(); DoublyLinkedList dll = new DoublyLinkedL
n
,作为行数。然后我们取n行输入。每行仅包含一个字符,可以是
或-
或一个小写英文字母。对于
或您不需要内部For循环。接受输入后立即处理输入
for (int i=0; i< n; i++)
arr[i] = sc.nextLine();
DoublyLinkedList dll = new DoublyLinkedList();
int cursor= 0;
if (arr[i].matches("[a-z]")){
dll.insertAtGivenPos(arr[i], cursor);
cursor++;
}
else if (arr[i].contains("-")&& dll.GetNth(cursor-1)!= null) {
dll.deleteNodeAtGivenPos(cursor);
cursor--;
}
else if (arr[i].contains("<") && dll.GetNth(cursor-1)!= null)
cursor--;
else if (arr[i].contains(">") && dll.GetNth(cursor+1)!= null)
cursor++;
}
for(int i=0;i
如果您没有被迫遵循实现细节,我建议不要使用光标。相反,保留一个变量currentNode
,该变量是光标将指向的节点。因此,对于输入循环中的每个命令(或数据),您有一个O(1)操作,如下所示,因此将获得O(n)时间复杂度
1-对于
:将当前节点更改为当前节点。下一步
2-对于这减少了时间,但我想这不会改变时间复杂度。我正在考虑改进我的类的方法。类似于插入和删除节点的方法。使用这种方法,我可以编写需要线性时间的代码。非常感谢你。
for (int i=0; i< n; i++)
arr[i] = sc.nextLine();
DoublyLinkedList dll = new DoublyLinkedList();
int cursor= 0;
if (arr[i].matches("[a-z]")){
dll.insertAtGivenPos(arr[i], cursor);
cursor++;
}
else if (arr[i].contains("-")&& dll.GetNth(cursor-1)!= null) {
dll.deleteNodeAtGivenPos(cursor);
cursor--;
}
else if (arr[i].contains("<") && dll.GetNth(cursor-1)!= null)
cursor--;
else if (arr[i].contains(">") && dll.GetNth(cursor+1)!= null)
cursor++;
}