题目:
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.
题意:
给定一个链表,删除倒数第k个节点。
思路:
这道题目,很直观的让人能够想到使用两个指针,其中一个先走k步的,那么当第二个指针走到链表最末尾的时候,那么第一个指针就走到了应该被删的那个位置。我们保存被删节点的前一个位置。然后就可以删除。
但是需要注意的是k可能不符合条件,比如k<=0或者k大于链表的长度。这些细节都是需要考虑到的。
以上。
代码如下:
/**
* 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 == NULL || n <= 0)return head;
ListNode* first = head, *second = head;
for (int i = 0; i < n - 1 && second != NULL; i++)
second = second->next;
if (second == NULL)return NULL;
ListNode* prev = NULL;
while (second->next != NULL) {
second = second->next;
prev = first;
first = first->next;
}
if (prev == NULL) {
head = head->next;
}
else prev->next = first->next;
return head;
}
};