在bash中,我能够编写一个包含如下内容的脚本:
{ time {
#series of commands
echo "something"
echo "another command"
echo "blah blah blah"
} } 2> $LOGFILE
在ZSH中,等效代码不起作用,我也想不出如何使它为我工作。这段代码可以工作,但我不知道如何让它包装多个命令。
{ time echo "something" } 2>&1
我知道我可以创建一个新的脚本,并将命令放在那里,然后正确地执行,但是是否有一种方法可以使用函数或类似于上述bash的方法?
你可以利用弗洛伊德的循环寻找算法,也被称为乌龟和兔子算法。
这个想法是有两个引用列表,并以不同的速度移动它们。一个1节点向前移动一个,另一个2节点移动。
如果链表有一个循环,他们一定会见面。
否则两个引用(或他们next)中的任何一个都会变成null。
实现该算法的Java函数:
boolean hasLoop(Node first) {
if(first == null) // list does not exist..so no loop eithe
return false;
Node slow, fast; // create two references.
slow = fast = first; // make both refer to the start of the list
while(true) {
slow = slow.next; // 1 hop
if(fast.next != null)
fast = fast.next.next; // 2 hops
else
return false; // next node null => no loop
if(slow == null || fast == null) // if either hits null..no loop
return false;
if(slow == fast) // if the two ever meet...we must have a loop
return true;
}
}
面是Fast / Slow解决方案的一个改进,它可以正确处理奇数长度的列表并提高清晰度。
boolean hasLoop(Node first) {
Node slow = first;
Node fast = first;
while(fast != null && fast.next != null) {
slow = slow.next; // 1 hop
fast = fast.next.next; // 2 hops
if(slow == fast) // fast caught up to slow, so there is a loop
return true;
}
return false; // fast reached null, so the list terminates
}