LeetCode OJ-19.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.
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个节点。虽然处理起来很直接,但还是要注意一些细节:在删除节点时,若待删除节点为表头节点,则直接返回head->next即可;若为表的中部节点,即该节点存在前驱后继节点,则要将其前驱节点的next值赋值为其后继节点;若为表尾节点,则将其前驱节点的next设置为空指针即可。至于位置的确定,可以用倒数链表长度的方式处理,具体的处理可以参考代码,细节也在注释中表明了。
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int list_cnt(ListNode *head) {
ListNode *cur = head;
int res = 0;
while (cur != 0) {
cur = cur->next;
++res;
}
return res;
}
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int sz = list_cnt(head);
int pos = sz;
if (pos == n) { // 去除表头节点的情况
return head->next;
}
else { // 去除表头以外的节点的情况
ListNode *last = head;
ListNode *cur = head;
while (pos != n) {
last = cur;
cur = cur->next;
--pos; // 倒数链表长度即可得到待删除节点的位置,这点可以自己写写验证下
}
if (cur->next != 0) { // 待去除节点后继节点存在
last->next = cur->next;
}
else { // 待去除节点为表尾
last->next = 0;
}
}
return head;
}
};