leetcode-Remove Nth Node From End of List
2015-03-09 22:05
197 查看
此题本来是十分简单的题目,可是由于自己对于指针以及函数参数的理解不是很透彻导致出现很多次问题,主要问题在于对函数传入指针参数,其实传入的是某指针的副本,通过指针的解引用可以修改指针指向的对象的内容,但是无法修改原指针所指的地址,如果要有修改原指针所指向的地址,那就应该传入指针的引用。对于此题,我开始并没有使用快慢指针,而是使用递归去解决的,下面贴入最初的错误代码和修改后pass的正确代码以示警醒:
错误的代码:
正确的代码:
错误的代码:
void changenext(ListNode *head,int n,int &k)//传入指针 { if(head==NULL) return; changenext(head->next,n,k); if(k==n) { head=head->next;//修改的是副本指针的地址 } k++; } ListNode *removeNthFromEnd(ListNode *head, int n) //使用递归 { int k=1; changenext(head,n,k); return head; }
正确的代码:
void changenext(ListNode *&head,int n,int &k)//传入指针的引用 { if(head==NULL) return; changenext(head->next,n,k); if(k==n) { head=head->next;//修改的是原指针的地址 } k++; } ListNode *removeNthFromEnd(ListNode *head, int n) //使用递归 { int k=1; changenext(head,n,k); return head; }还有一点值得注意的是,本问题之所以会产生,是因为原题给定的环境中链表没有附加头结点,所以为了统一只能这么写,还可以通过添加附加头结点的方法来解决这个问题,这时候只需要修改指针指向的内容,即修改ptr->next便能统一的解决这个问题,代码如下:
void changenext(ListNode *head,int n,int &k) { if(head==NULL) return; changenext(head->next,n,k); if(k==n+1) { head->next=head->next->next; } k++; } ListNode *removeNthFromEnd(ListNode *head, int n) //使用递归 { ListNode *first=new ListNode(0);//为原链表添加附加头结点,以便处理起来的同一方便 first->next=head; int k=1; changenext(first,n,k); return first->next; }
相关文章推荐
- leetcode -- Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List 解题报告
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- LeetCode 笔记系列四 Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- [leetcode]Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [leetcode刷题系列]Remove Nth Node From End of List
- leetcode--Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List