Redian新闻
>
Careercup书第四版一道题的解答有错
avatar
Careercup书第四版一道题的解答有错# JobHunting - 待字闺中
j*l
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
}
avatar
H*X
2
这本书的答案都是从网页上的回答选的。。大概也就是给你一个思路。
avatar
d*e
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;
: }

avatar
l*a
4
en
这题就没必要看答案了,自己写吧
PIE上应该是正确的

【在 H*X 的大作中提到】
: 这本书的答案都是从网页上的回答选的。。大概也就是给你一个思路。
avatar
d*e
5
PIE是哪里?

【在 l*****a 的大作中提到】
: en
: 这题就没必要看答案了,自己写吧
: PIE上应该是正确的

avatar
l*a
6
programmer interview exposed

【在 d**e 的大作中提到】
: PIE是哪里?
avatar
H*X
7
PIE貌似也有小错,我记得lz也发帖谈过,不过总体来说,pie的答案靠谱多了,不光有
code,还有讲解
avatar
l*a
8
这种思路很明确的题正好自己写,自己给出test cases。。

【在 H*X 的大作中提到】
: PIE貌似也有小错,我记得lz也发帖谈过,不过总体来说,pie的答案靠谱多了,不光有
: code,还有讲解

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。