我正在编写一个代码,如果整个链接列表结实,则返回true,如果不是,则返回false。一个口吃的列表是1,1,2,2,5,5,8,8
,非破坏的列表就像1,1,2,2,5,6,8,8
。
我已经玩了很长一段时间了,似乎无法让它返回正确的语句或者没有得到nullpointer异常。
public boolean foo(){
ListNode current = front;
ListNode runner = current.next;
while (current.next.next!=null){ //Looks two ahead for the end
if(current.data!=runner.data){ //They aren't equal, false
System.out.println(current.data); //just to see my data
System.out.println(runner.data); //debugging only
return false;
}
current = current.next.next; //increase by 2
runner = runner.next.next; // increase by 2
System.out.println(current.data + " ||" + runner.data); //again debugging
}
return true; // didn't register false, go ahead and true dat badboy.
}
public static void main (String[] args){
LinkedIntList list = new LinkedIntList();
list.add(1);
list.add(1);
list.add(3);
list.add(3);
list.add(5);
list.add(5);
System.out.println(list.foo());
}
有人在这里看到明显的错误吗?我已经尝试为current.next运行我的while循环,以及每次增加我的跑步者和当前的一个而不是两个,但没有一个有效。
答案 0 :(得分:3)
如果没有先检查,您不能盲目地使用current.next.next
,因为current
或current.next
完全可能为空。
如果是这种情况,你会得到一个空指针问题。
假设口吃只意味着双倍(根据你的例子)而不是任何倍数,那么用以下算法可以更好地降低:
def isStuttered(node):
while node != null:
# Check if only one item left.
if node.next == null:
return false
# Check if not a pair.
if node.data != node.next.data:
return false
# Advance to next pair, okay as we have 2+ items left.
node = node.next.next
return true
stuttered = isStuttered(head)
顺便说一句,如果“断断续续”意味着每个项目有两个或更多,那么对算法的一个小改动:
def isStuttered(node):
while node != null:
# Check if only one item left.
if node.next == null:
return false
# Check if not at least two.
val = node.data
if val != node.next.data:
return false
# Start with second item in set,
# advance to either new value or list end.
node = node.next
while node != null # note 'and' must short-circuit
and node.data == val:
node = node.next
return true
答案 1 :(得分:1)
而不是while (current.next.next!=null)
,请检查while (runner.next!=null)
。此外,您必须在while
循环后匹配最后两个节点的数据。
假设您的问题中提到的列表具有偶数个元素,则代码中的以下更改将产生正确的输出。
public boolean foo(){
ListNode current = front;
ListNode runner = current.next;
while (runner.next!=null){ //Looks two ahead for the end
if(current.data!=runner.data){ //They aren't equal, false
System.out.println(current.data); //just to see my data
System.out.println(runner.data); //debugging only
return false;
}
current = current.next.next; //increase by 2
runner = runner.next.next; // increase by 2
System.out.println(current.data + " ||" + runner.data); //again debugging
}
if(current.data!=runner.data){ //They aren't equal, false
System.out.println(current.data); //just to see my data
System.out.println(runner.data); //debugging only
return false;
}
return true; // didn't register false, go ahead and true dat badboy.
}
更好的&干净的实施如下:
public boolean foo(){
ListNode current = front;
while (current != null){
if(current.next == null)
return false;
if(current.data != current.next.data)
return false;
current = current.next.next;
}
return true;
}