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.
Follow up:
Could you do this in one pass?
关键:
1、三个指针,一个用于找到链表尾节点,ListNode* front;一个用于指向被删除节点,ListNode* del;一个用于指向被删除节点前一个节点,ListNode* back。
2、front先往前移动n步,然后front,del和back一起移动。
3、三种特殊情况,链表长度为0;链表长度为1;删除的节点是头节点。
/** * 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->next==NULL){ return NULL; } ListNode* front=head; ListNode* del=head; ListNode* back=NULL; for(int i=0;i<n;i++){ front=front->next; } while(front!=NULL){ front=front->next; back=del; del=del->next; } if(back==NULL){ return del->next; }else{ back->next=back->next->next; return head; } } };