j**l 发帖数: 2911 | 1 2.2 Implement an algorithm to find the nth to last element of a singly
linked list.
考虑一个元素的链表,n = 2
则for语句执行一次,循环结束后p2为null
然后while语句试图取null指针的next值,crash...
错误代码如下
LinkedListNode nthToLast(LinkedListNode head, int n) {
if (head == null || n < 1) {
return null;
}
LinkedListNode p1 = head;
LinkedListNode p2 = head;
for (int j = 0; j < n - 1; ++j) { // skip n-1 steps ahead
if (p2 == null) {
return null; // not found since list size < n
}
|
H*X 发帖数: 281 | 2 这本书的答案都是从网页上的回答选的。。大概也就是给你一个思路。 |
d**e 发帖数: 6098 | 3 够细心……
改成这样?
int i = 0;
while(p2->next && i < n)
{
p2 = p2->next;
i++;
}
if(i < n)
return NULL;
while(p2->next)
{
p2 = p2->next;
p1 = p1->next;
}
return p1;
【在 j**l 的大作中提到】 : 2.2 Implement an algorithm to find the nth to last element of a singly : linked list. : 考虑一个元素的链表,n = 2 : 则for语句执行一次,循环结束后p2为null : 然后while语句试图取null指针的next值,crash... : 错误代码如下 : LinkedListNode nthToLast(LinkedListNode head, int n) { : if (head == null || n < 1) { : return null; : }
|
l*****a 发帖数: 14598 | 4 en
这题就没必要看答案了,自己写吧
PIE上应该是正确的
【在 H*X 的大作中提到】 : 这本书的答案都是从网页上的回答选的。。大概也就是给你一个思路。
|
d**e 发帖数: 6098 | 5 PIE是哪里?
【在 l*****a 的大作中提到】 : en : 这题就没必要看答案了,自己写吧 : PIE上应该是正确的
|
l*****a 发帖数: 14598 | 6 programmer interview exposed
【在 d**e 的大作中提到】 : PIE是哪里?
|
H*X 发帖数: 281 | 7 PIE貌似也有小错,我记得lz也发帖谈过,不过总体来说,pie的答案靠谱多了,不光有
code,还有讲解 |
l*****a 发帖数: 14598 | 8 这种思路很明确的题正好自己写,自己给出test cases。。
【在 H*X 的大作中提到】 : PIE貌似也有小错,我记得lz也发帖谈过,不过总体来说,pie的答案靠谱多了,不光有 : code,还有讲解
|