题目:19. Remove Nth Node From End of List
Difficulty:Medium
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.
题意:
第一个单链表,移除倒数第n个元素,返回移除后的链表的头节点。
分析:
本题思路很简单,从后往前数到第n个元素移除,然后返回头节点即可。但是因为是单链表 不支持从后向前访问,因此这里可以借助一些其它的容器暂存,然后重构移除后的单链表并返回头节点即可。实现见Code1:
第二种思路也很简单,既然是要移除倒数第n项,那么所要移除的那一项后面必然还有n-1个元素,所以,可以借助两个指针,使得两个指针之间间隔n+1个元素,当后一个元素到达末尾时,前一个元素所指向的元素即为要删除节点的前一个节点从而不需要借助其他容器即可实现。实现见Code2.
Code
/**
* 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)return head;
ListNode *first = head, *tmp;
deque<ListNode *> node;
while(first!=NULL){
tmp = first;
node.push_back(tmp);
first = first->next;
}
while(!node.empty()){
--n;
if (n==0){
node.pop_back();
continue;
}
tmp = node.back();
node.pop_back();
tmp->next = first;
first = tmp;
}
return first;
}
};
这里使用了双端队列,重构移除后的单链表时采用的是头插法,不过按照本题的题意,使用stack(先进后出)应该会更合适一点,不过两者的效率应该的相差无几。结果如下:
Runtime: 8 ms, faster than 100.00% of C++ online submissions for Remove Nth Node From End of List.
Memory Usage: 10 MB, less than 5.27% of C++ online submissions for Remove Nth Node From End of List.
Code2
/**
* 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)return head;
if(head->next==NULL && n==1) return NULL;
ListNode *ans = new ListNode(0);
ans->next = head;
ListNode *pre=ans, *first = ans;
while(n>=0 && first!=NULL){
--n;
first=first->next;
}
while(first!=NULL){
first = first->next;
pre = pre->next;
}
pre->next = pre->next->next;
return ans->next;
}
};
Runtime: 8 ms, faster than 100.00% of C++ online submissions for Remove Nth Node From End of List.
Memory Usage: 9.8 MB, less than 26.69% of C++ online submissions for Remove Nth Node From End of List.
通过以上结果可以看出两者对比仅空间复杂度略有改善。不过也是一种可以学习的解题方法。
Code2 & Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
ans = ListNode(0)
ans.next = head
first, second = head, ans
for i in range(n):
first = first.next
while first is not None:
first = first.next
second = second.next
second.next = second.next.next
return ans.next
结果:
Runtime: 44 ms, faster than 49.47% of Python3 online submissions for Remove Nth Node From End of List.
Memory Usage: 13.4 MB, less than 5.60% of Python3 online submissions for Remove Nth Node From End of List.