Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中使用双链表创建移动光标_Java_Data Structures_Time Complexity_Doubly Linked List - Fatal编程技术网

在java中使用双链表创建移动光标

在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

我正试图用java编写一个简单移动光标的代码。我必须使用双链表。我还应该自己实现doubyLinkedList类。在这个程序中,我们首先从用户那里获取一个整数,如
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++;
}