LeetCode: Remove Nth Node From End of List [019]
2014-05-16 13:49
337 查看
【题目】
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个结点【思路】
维护两个指针p1,p2,初始时都指向首节点。p2结点先向前移动n步,然后两个指针同时向后移动,直至p2指向队尾的空指针。此时p1指向的即为需要删除的指针。为了完成操作,还需要额外维护一个指向p1前一个结点的prev指针。【代码】
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { ListNode*prev=NULL; ListNode*p1=head; ListNode*p2=head; int k=0; while(k<n && p2){k++;p2=p2->next;} if(k<n)return head; //链表元素少于n个,则不做删除操作 //定位待待删除元素 while(p2){ prev=p1; p1=p1->next; p2=p2->next; } //删除元素 if(prev)prev->next=p1->next; else head=p1->next; return head; } };
相关文章推荐
- 2017-09-10 LeetCode_019 Remove Nth Node From End of List
- LeetCode019 Remove Nth Node From End of List
- LeetCode 019 Remove Nth Node From End of List
- LeetCode 019 Remove Nth Node From End of List
- [LeetCode]题解(python):019-Remove Nth Node From End of List
- leetcode019 Remove Nth Node From End of List
- leetcode 019 Remove Nth Node From End of List (Python)
- 【JAVA、C++】LeetCode 019 Remove Nth Node From End of List
- [LeetCode]019-Remove Nth Node From End of List
- LeetCode 019 Remove Nth Node From End of List
- LeetCode 019 Remove Nth Node From End of List
- leetcode_c++:链表:Remove Nth Node From End of List(019)
- 【LeetCode-面试算法经典-Java实现】【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】
- 019 Remove Nth Node From End of List [Leetcode]
- leetcode 019 —— Remove Nth Node From End of List
- [面试真题] 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