Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解c++版本的P44页有问题 #27

Open
aCayF opened this issue Aug 12, 2014 · 3 comments
Open

LeetCode题解c++版本的P44页有问题 #27

aCayF opened this issue Aug 12, 2014 · 3 comments

Comments

@aCayF
Copy link

aCayF commented Aug 12, 2014

P44页讲到了Remove Duplicates from Sorted List的迭代解法,其中的一段代码片段:

for (ListNode *prev = head, *cur = head->next; cur; cur = cur->next) {
    if (prev->val == cur->val) {
        prev->next = cur->next;
        delete cur;
    } else {
        prev = cur;
    }
}

既然delete cur语句已经将cur删除,为什么还可以在for的条件语句里执行cur = cur->next?

PS.感谢作者辛勤的劳动为我们带来了如此有价值的作品,再次感谢:)

@soulmachine
Copy link
Owner

Delete cur 后,cur 所指向的对象释放了,但cur只是个名字,这个名字还是可以复用的

On Tuesday, August 12, 2014, Lice Pan [email protected] wrote:

P44页讲到了Remove Duplicates from Sorted List的迭代解法,其中的一段代码片段:

for (ListNode *prev = head, *cur = head->next; cur; cur = cur->next) {
if (prev->val == cur->val) {
prev->next = cur->next;
delete cur;
} else {
prev = cur;
}}

既然delete cur语句已经将cur删除,为什么还可以在for的条件语句里执行cur = cur->next?

PS.感谢作者辛勤的劳动为我们带来了如此有价值的作品,再次感谢:)


Reply to this email directly or view it on GitHub
#27.

My tech blog: http://www.soulmachine.me
My GitHub: https://github.com/soulmachine
My LinkedIn: http://www.linkedin.com/in/soulmachine/
My Sina Weibo: http://weibo.com/soulmachine

@aCayF
Copy link
Author

aCayF commented Aug 15, 2014

delete cur之后cur->next还能引用?本人c++菜鸟,望指教:)

@riveridea
Copy link

这个问题我有看法,delete cur之后,cur当然那还能被附新值,但是继续使用cur->next 赋值且程序通过的原因是cur原来指向的内存没有被其他程序污染,所以可以找到cur->next,其实这样写是不太妥当的,我改成了下面这个写法,功能一样,就是防止面试官质疑:

class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL) return NULL;

    for(ListNode *prev = head, *curr = head->next;
        curr;
        curr = curr->next){
            if(prev->val == curr->val){
                ListNode *next = curr->next;
                prev->next = next;
                delete curr;
                curr = prev; 
            }
            else{
                prev = curr;
            }
        }
    return head;
}

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants