LeetCode--Remove Nth Node From End of List

题目描述:

Given a linked list, remove the n-th node from the end of list and return its head.

note:

Given n will always be valid.

样例:

1
2
3
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.

题意:

给出一个链表,移除并返回删除后的链表

思路:

直接两个指针 p、q,p 先遍历前面 n 个节点,然后 p、q 一起遍历,直到 p 遍历到最后一个节点,删除当前的 q 节点

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* 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(n == 0) return head;
if(head == NULL) return head;
ListNode *pl = head, *pr = head;
for(int i = 1; i <= n; ++i) pr = pr->next;
if(pr == NULL) {
head = head->next;
return head;
}
while(pr->next != NULL){
pr = pr->next;
pl = pl->next;
}
pl->next = pl->next->next;
return head;
}
};

Runtime:8ms Memory:9.5MB