繁体   English   中英

有没有一种方法可以从链表末尾的索引中找到一个元素

[英]Is there a way to find an element in a linked-list by its index from the end of it

我有一个非循环链表数据结构。 像这样:

public class LinkLst<T>{
    private Node<T> first;

    public LinkLst(T t){
        first = new Node(t);
    }
}

public class Node<T>{
    private T t;
    private Node<T> next;

    public Node(T t){
        this.t = t;
    }

    public void setNext(Node<T> n){
         this.next = next;
    }
}

因此,我们知道默认情况下列表不包含循环。 有没有一种方法可以从LinkLst<T> lst的末尾找到第n个元素,如果n <= size(lst)仅进行一次迭代,并且如果n > size(lst)则抛出IndexOutOfBoundException

public <T> T fromTheEnd(LinkLst<T> lst, int n){
   //...?
}

我唯一能找到的就是反转它,然后找到所需的元素,但是它需要2次迭代。 一种用于反向,另一种用于查找所需的元素。 还有内存开销。

public <T> T fromTheEnd(LinkList<T> ts, int idx) {
    Node<T> follower, leader;
    // We iterate until the leader hits the end of the list. follower follows leader
    // idx steps behind, so when leader.next = [], follower is the desired node.
    follower = leader = ts.first;
    for(int j = 0; j < idx; j++) {
        leader = leader.next;
    }
    // leader is now idx steps ahead
    while(leader.next != null) {
      leader = leader.next;
      follower = follower.next;
    }
    // leader has hit the end (next is null)
    // follower has your data
    return follower.t;
}

本质上,这是具有两个“头”的单个迭代。

索引的例子2[1, 2, 3, 4, 5]从端部。

Setup:
[1, 2, 3, 4, 5]
 ^ Leader
 ^ Follower

First loop:
[1, 2, 3, 4, 5]
 ^ F   ^ L

Second loop round 0:
[1, 2, 3, 4, 5]
    ^ F   ^ L

Second loop round 1:
[1, 2, 3, 4, 5]
       ^ F   ^ L

Loop ends: next(leader) = []
deref(follower) = 3

您可能需要排除方法<T> LinkList<T> last(LinkList<T>, int) ,该方法返回具有给定长度的列表后缀,该方法可以将fromTheEnd表示为last(ts, n).first.t

如果不想重复两次,则必须记住n值,这需要内存。 这是否比迭代两次更好?

创建大小为n的数组,并在迭代列表时以循环方式将值添加到数组。

当到达列表的末端,并至少n元件已被迭代,第n-从-最后一个元素是在环阵列中的下一个位置。

这牺牲了性能的记忆。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM