1. 概述
1.1 题目
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.
1.2 解题思路
思路1:这道题时要求去除从倒数开始的第n个字符,由于不知道链表的个数有多少,只有先去遍历一遍得到大小,再由n指定去除的元素,再将断开的链表连接起来。
思路2:定义一个前指针和一个后指针,他们之间的间隔正好n个数字。首先链表就先走n步,然后判断最前面的指针的下一个是不是到末尾了,要是到了末尾就是返回头指针的下一个;否则一前一后的两个指针那就一步步往下走,知道前面指针的下一个为空,然后将后指针的下一个与下下一个相连。
但是从代码运行的时间来说第一种方式还比第二种方式快了3ms -_-||
2. 编码
2.1 方法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 == nullptr) return head; //要是头指针为空,返回头指针
if(0 == n) return head;
//方法1
vector<ListNode*> vec; //指针容器,用于计算倒数第n个指针位置
ListNode* p = head; //迭代指针
while(nullptr != p)
{
vec.push_back(p); //记录指针
p = p->next; //指向下一个指针位置
}
int vec_size(vec.size()); //确定指针的数目
if(n == vec_size) return head->next;
p = vec[vec_size-n]; //指向需要删除的指针
ListNode* p_next = p->next; //指向删除指针的下一个
ListNode* p_pre = vec[vec_size-n-1]; //指向删除指针的上一个
p_pre->next = p_next; //连接指针链
delete p;
p = nullptr;
return head;
}
};
2.2 方法2
/**
* 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 == nullptr) return head; //要是头指针为空,返回头指针
if(0 == n) return head;
//方法2
ListNode* back = head; //一前一后两个指针
ListNode* front = head;
for(int i=0; i<n; ++i) //先走n步再说
front = front->next;
if(nullptr == front) return head->next; //走了n步发现front到尾巴了,那么back就是要删除的元素了,返回它指向的下一个
while(nullptr != front->next)
{
front = front->next;
back = back->next;
}
back->next = back->next->next;
return head;
}
};