[Leetcode 19, Easy] Remove Nth Node From End of List
2015-02-23 10:41
489 查看
Problem:
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.
Analysis:
The key idea to this problem that the two pointers that we assigned for this linked list should have distance n nodes. Then the back pointer will point to the node we need to remove when the front point point to the last node of this linked list.
Solution:
C++:
Java:
Python:
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.
Analysis:
The key idea to this problem that the two pointers that we assigned for this linked list should have distance n nodes. Then the back pointer will point to the node we need to remove when the front point point to the last node of this linked list.
Solution:
C++:
ListNode *removeNthFromEnd(ListNode *head, int n) { if(n == 0) return head; ListNode* pBack = head; ListNode* pFront = head; for(int i = 0; i < n; ++i) { pFront = pFront->next; } if(pFront == NULL) { head = pBack->next; delete pBack; return head; } while(pFront->next != NULL) { pFront = pFront->next; pBack = pBack->next; } ListNode* pDelete = pBack->next; pBack->next = pBack->next->next; delete pDelete; return head; }
Java:
Python:
相关文章推荐
- [leetcode] 19. Remove Nth Node From End of List python实现【easy】
- Leetcode 19. Remove Nth Node From End of List (Easy) (cpp)
- leetcode_19_Remove Nth Node From End of List (easy)
- [Leetcode 19, Easy] Remove Nth Node From End of List
- LeetCode-19-Remove Nth Node From End of List(链表)-Easy
- LeetCode 19: Remove Nth Node From End of List
- leetcode[19]Remove Nth Node From End of List
- leetcode19-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
- 19. Remove Nth Node From End of List Leetcode Python
- LeetCode 19. Remove Nth Node From End of List
- 【LeetCode】19. Remove Nth Node From End of List (2 solutions)
- [Leetcode 19] 19 Remove Nth Node From End Of List
- 【leetcode】Remove Nth Node From End of List(easy)
- [Leetcode] 19. Remove Nth Node From End of List
- [leetcode 19] Remove Nth Node From End of List
- 【Leetcode】【Easy】Remove Nth Node From End of List
- Leetcode[Easy] - Remove Nth Node From End of List
- [leetcode 19] Remove Nth Node From End of List