Description
Given a linked list, remove the nth node from the end of list and return its head.
Example
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.
思路
- 边界情况主要最第一个和最后一个的处理
- 先遍历链表,找出链表长度
- 然后计算出要删除的节点的前一个节点
- 此时,需要分清楚是否是删除第一个节点。然后就没有然后了
代码
/**
* 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) return NULL;
ListNode *ptr = head;
int len = 0;
while(ptr){
ptr = ptr->next;
len++;
}
ptr = head;
int tmp = len - n;
n = tmp;
cout << tmp << endl;
while(tmp > 1){
ptr = ptr->next;
tmp--;
}
if(n > 0){
if(ptr->next){
ListNode *tmp = ptr->next;
ptr->next = tmp->next;
delete tmp;
}
else ptr->next = NULL;
}
else
{
ListNode *tmp = head;
head = head->next;
delete tmp;
}
return head;
}
};