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

For example,

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.

链表的操作,对头尾进行删除时需要特殊处理,也可采用在头部再增加一个节点,就只需要对删尾节点做特殊处理

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* 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) {
int len = getLength(head);
if (len == 0 || n < 1)
return head;

if (len == n) {
if (len == 1) {
return NULL;
} else {
return head->next;
}
}

ListNode* p = head;
for (int i = 0; i < len - n - 1; i++) {
p = p->next;
}
ListNode* deleted = p->next;
p->next = (n == 1 ? NULL : deleted->next);
delete deleted;
return head;
}

int getLength(ListNode* head) {
int len = 0;
while (head) {
len ++;
head = head->next;
}
return len;
}
};