https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
19. 删除链表的倒数第 N 个结点
难度中等1625
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1 输出:[]
示例 3:
输入:head = [1,2], n = 1 输出:[1]
提示:
- 链表中结点的数目为
sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
/**
* 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) {
}
};
#include <iostream>
#include <cassert>
using namespace std;
///Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// LinkedList Test Helper Functions
ListNode* createLinkedList(int arr[], int n){
if(n == 0)
return NULL;
ListNode* head = new ListNode(arr[0]);
ListNode* curNode = head;
for(int i = 1 ; i < n ; i ++){
curNode->next = new ListNode(arr[i]);
curNode = curNode->next;
}
return head;
}
void printLinkedList(ListNode* head){
if(head == NULL){
cout<<"NULL"<<endl;
return;
}
ListNode* curNode = head;
while(curNode != NULL){
cout << curNode->val;
if(curNode->next != NULL)
cout << " -> ";
curNode = curNode->next;
}
cout << endl;
return;
}
void deleteLinkedList(ListNode* head){
ListNode* curNode = head;
while(curNode != NULL){
ListNode* delNode = curNode;
curNode = curNode->next;
delete delNode;
}
return;
}
/// Get the total length and remove the nth node
/// Two Pass Algorithm
///
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
int length = 0;
for(ListNode* cur = dummyHead->next ; cur != NULL ; cur = cur->next)
length ++;
int k = length - n;
assert(k >= 0);
ListNode* cur = dummyHead;
for(int i = 0 ; i < k ; i ++)
cur = cur->next;
ListNode* delNode = cur->next;
cur->next = delNode->next;
delete delNode;
ListNode* retNode = dummyHead->next;
delete dummyHead;
return retNode;
}
};
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(int);
ListNode* head = createLinkedList(arr, n);
printLinkedList(head);
head = Solution().removeNthFromEnd(head, 2);
printLinkedList(head);
deleteLinkedList(head);
return 0;
}