Leetcode 19. Remove Nth Node From End of List
2018-01-30 09:58
337 查看
原题:
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Note:
Given n will always be valid.
Try to do this in one pass.
解决方法:
用前后指针的方法来解这道题,通用第二个指针是指向指针的指针,这样可以直接修改直接的值。
第一个指针先往前走n-1步,然后两个指针一起往前走,直到第一个指针的下一个指针为空,那第二个指针的位置就是当前需要删除的指针。将其指向下一个指针,相当于将该指针删除。
代码:
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
解决方法:
用前后指针的方法来解这道题,通用第二个指针是指向指针的指针,这样可以直接修改直接的值。
第一个指针先往前走n-1步,然后两个指针一起往前走,直到第一个指针的下一个指针为空,那第二个指针的位置就是当前需要删除的指针。将其指向下一个指针,相当于将该指针删除。
代码:
ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* l1 = head, **l2 = &head; for(int i = 1; i < n; i++) l1 = l1->next; while(l1->next != NULL){ l1 = l1->next; l2 = &( (*l2)->next); } *l2 = (*l2)->next; return head; }
相关文章推荐
- leetcode 19. Remove Nth Node From End of List-移除链表元素|双指针
- [Leetcode] 19. Remove Nth Node From End of List
- Leetcode 19. Remove Nth Node From End of List(python)
- LeetCode 19. Remove Nth Node From End of List
- LeetCode 19 - Remove Nth Node From End of List
- Leetcode 19. Remove Nth Node From End of List (Easy) (cpp)
- LeetCode41/19 First Missing Positive/Remove Nth Node From End of List ****
- leetcode - 19.Remove Nth Node From End of List
- leetcode[19]Remove Nth Node From End of List
- Leetcode 19. Remove Nth Node From End of List
- leetcode 19 Remove Nth Node From End of List
- LeetCode之19---Remove Nth Node From End of List
- leetcode 19 Remove Nth Node from end of list
- leetcode 19. Remove Nth Node From End of List
- LeetCode --- 19. Remove Nth Node From End of List
- leetcode 19 -- Remove Nth Node From End of List
- [LeetCode]19. Remove Nth Node From End of List
- [LeetCode] 19. Remove Nth Node From End of List 删除链表的倒数第N个节点 @python
- Leetcode 19 Remove Nth Node From End of List
- LeetCode19——Remove Nth Node From End of List