leetcode_19题——Remove Nth Node From End of List(链表)
2015-05-27 09:57
393 查看
Remove Nth Node From End of List
Total Accepted: 54129 Total Submissions: 197759My SubmissionsQuestion Solution
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.
Hide Tags
Linked List Two Pointers
Have you met this question in a real interview?
Yes
No
Discuss
这道题题目要求删除链表中指定的倒数第n个结点,并且采用一次遍历,所以应该采用两个指针的方法
先将指针ptr1和ptr2之间的距离弄成n,再往后同时后移,而由于涉及到结点的删除,还要弄一个指针指到ptr1的前面那个结点处就可以了,
这道题要考虑到结点删除时是尾结点还是头结点还是中间结点
#include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *ptr1,*ptr2,*ptr0; ptr0=head; ptr1=head; ptr2=head; int N=n-1; while(N--) ptr2=ptr2->next; if(ptr2->next==NULL) if(ptr1->next!=NULL) return ptr1->next; else return NULL; ptr1=ptr1->next; ptr2=ptr2->next; while(ptr2->next!=NULL) {ptr2=ptr2->next;ptr1=ptr1->next;ptr0=ptr0->next;} if(n==0) {ptr1->next=NULL;return head;} ptr0->next=ptr1->next; return head; } int main() { }
相关文章推荐
- 【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个节点
- 【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
- leetCode 19. Remove Nth Node From End of List 链表
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- LeetCode 19. Remove Nth Node From End of List--删除链表的倒数第n个结点
- [LeetCode-19] Remove Nth Node From End of List(删除链表中倒数第N个节点)
- 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项)
- leetcode_[python/C++]_19. Remove Nth Node From End of List(删除链表末第n个节点)
- [LeetCode] 19. Remove Nth Node From End of List 删除链表的倒数第N个节点 @python
- 面试题15:链表中倒数第k个节点(Leetcode-19:Remove Nth Node From End of List)
- 【LeetCode题解】19_删除链表的倒数第N个节点(Remove-Nth-Node-From-End-of-List)
- Leetcode:19 Remove Nth Node From End of List(在链表中删除倒数第n个数)
- LeetCode 19. Remove Nth Node From End of List(删除链表)
- 1.1数组和链表:19. Remove Nth Node From End of List(Leetcode)