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.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
struct ListNode* fast = head;
struct ListNode* slow = head;
while (fast != NULL)
{
fast = fast->next;
if (n-- < 0)
slow = slow->next;
}
if (n == 0)
{
/*free head if necessary*/
head = head->next;
}
else
{
/*free slow->next if necessary*/
slow->next = slow->next->next;
}
return head;
}
2021.06.20更新
/**
* 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) {
ListNode* dummy = new ListNode(-1,head);
ListNode* fast = head,*slow = dummy;
for(int i = 0;i < n;i++)
{
if(fast)
fast = fast->next;
}
while(fast)
{
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummy->next;
}
};
执行效率:
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:10.4 MB, 在所有 C++ 提交中击败了26.30%的用户
进一步优化代码:
/**
* 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) {
ListNode* dummy = new ListNode(-1,head);
ListNode* fast = head,*slow = dummy;
while(fast)
{
fast = fast->next;
if(--n < 0)
slow = slow->next;
}
slow->next = slow->next->next;
return dummy->next;
}
};
class Solution {
public:
int divide(int dividend, int divisor) {
if (dividend == INT_MIN && divisor == -1) {
return INT_MAX;
}
long dvd = labs(dividend), dvs = labs(divisor), ans = 0;
int sign = dividend > 0 ^ divisor > 0 ? -1 : 1;
while (dvd >= dvs) {
long temp = dvs, m = 1;
while (temp << 1 <= dvd) {
temp <<= 1;
m <<= 1;
}
dvd -= temp;
ans += m;
}
return sign * ans;
}
};