题目链接:Remove Nth Node From End of List
- 题目描述:
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
, andn = 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.
(1)思路:注意只能进行一次遍历就得出结果。那么可以使用两个指针始终保持n距离,当一个指针移动到链表尾部时,另外一个指针指向要删除元素的前一个,那么删除它的下一个节点。
(2)代码:
/**
* 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) {
if (head->next==NULL) return NULL;
ListNode *p = head, *q = head;
while(n--) q = q->next;
if (q == NULL) return head->next;
while(q->next) {
q = q->next;
p = p->next;
}
p->next = p->next->next;
return head;
}
};