Last Updated: 2023-10-19 12:04:30 Thursday
-- TOC --
不用太在意是one pass,还是two pass,都是一样的Big-Oh。我觉得two pass更好,不存在申请内存的动作。但转array之后的one pass,这个转array的思路,也许在其它场景下,更有用处。
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
输入不是Python的list,这里只是示意,输入是最麻烦的singly-linked list。
Constraints:
- The number of nodes in the list is sz.
- 1 <= sz <= 30
- 0 <= Node.val <= 100
- 1 <= n <= sz
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
nexts = []
p = head
while p:
nexts.append(p)
p = p.next
if len(nexts) == n:
return head.next
nexts[-n-1].next = nexts[-n].next
return head
无论如何都要遍历一次这个链表,干脆singly-linked list转真正的list,最后一行代码搞定!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
vector<ListNode*> arrNode;
arrNode.reserve(64);
ListNode *p { head };
while(p){
arrNode.push_back(p);
p = p->next;
}
size_t s { arrNode.size() } ;
if(n == s)
return head->next;
arrNode[s-n-1]->next = arrNode[s-n]->next;
return head;
}
};
C语言没有内置的容器,就不适合转array的思路。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
int size = 0;
struct ListNode *p = head;
while(p){
++size;
p = p->next;
}
if(size == n)
return head->next;
int move = size-n-1;
p = head;
while(move != 0){
p = p->next;
--move;
}
p->next = p->next->next;
return head;
}
本文链接:https://cs.pynote.net/ag/leetcode/202310171/
-- EOF --
-- MORE --