Given a linked list, remove the n-th node from the end of list and return its head.
給一個linked list,移除掉從後面數過來第n個數字並回傳list的起點。
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.
n
步,接著兩個一起跑,當第一個到底的時候,第二個所指的就是要移除的數字了。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* temp = head;
int s=0;
for(;temp;s++)
temp=temp->next;
n=s-n;
temp = head;
if(n==0) return head->next;
for(int i=0;i<n-1;i++)
temp = temp->next;
if(temp->next)
temp->next = temp->next->next;
return head;
}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* first = head;
for(int i=0;i<n;i++)
first=first->next;
if(!first)
return head->next;
ListNode* second = head;
for(;first->next;first=first->next)
second=second->next;
if(second->next)
second->next=second->next->next;
return head;
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up