题目:
Given a linked list, remove the n-th node from the end of list and return its head.
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.
代码:
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
ListNode* removeNthFromEnd(ListNode* head, int n) {
int count = 1;
ListNode* p = head;
while (p->next != NULL) {
count++;
p = p->next;
}
int mn = count - n;
if (mn == 0)return head->next;
ListNode* o = head;
ListNode* k = o->next;
for (int i = 1; i < mn; i++) {
o = k;
k = o->next;
}
if (k == NULL)return NULL;
o->next = k->next;
return head;
}
int main() {
ListNode n1(1);
ListNode n2(2);
ListNode n3(3);
ListNode n4(4);
ListNode n5(5);
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
ListNode* p = removeNthFromEnd(&n1, 1);
while (p != NULL) {
cout << p->val << " ";
p = p->next;
}
return 0;
}
注意事项:
1、考虑元素全部删完的情况
2、考虑删除的是头元素的情况