一、问题描述
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.
二、解题思路
首先定义preHead指向head,方便最后的返回;
head先走n步(因为初始时head就指向了1,所以只需要走n-1步即可),之后head的作用其实相当于尾指针了。主要用来判断链表是否走到了结尾。然后preN和head同时移动。当head移动到尾部时。此时,preN指向n结点的前一个位置。最后,只需要改变preN的next为n的next即可。
三、代码实现
/**
* 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* preHead = new ListNode(0);
preHead->next = head;
//preN永远是N的前一个结点
ListNode* preN = preHead;
int i = 1;
while(i < n) {
head = head->next;
i++;
}
while(head->next != NULL){
preN = preN->next;
head = head->next;
}
//经过while后,preN指向的就是结点3,所以只需要将3指向5就可以了
preN->next = preN->next->next;
return preHead->next;
}
};