难度:中等
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
题目解析:
首先遍历整个链表,计算出总的节点数,然后分情况讨论:1.如果n大于总结点数,那么直接返回;2.如果n等于总结点数,那么是删除首节点,需要用到临时节点;3.如果n小于总结点数,那么是正常情况,删除count-n的下一个节点
参考代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <unordered_map>
#include <cstring>
#include <map>
#include <stdexcept>
using namespace std;
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* temp_head = new ListNode(-1);
temp_head->next = head;
ListNode* pMove = head;
int count = 0;
//遍历整个链表,计算总结点数
while (pMove)
{
count++;
pMove = pMove->next;
}
//分情况讨论,n大于总结点数,直接返回,没有要删除的目标
if (n > count)
return head;
//n等于总结点数,那么删除首节点
if (n == count)
{
temp_head->next = head->next;
}//n小于总结点数,删除count-n的下一个节点
else if (n < count)
{
pMove = head;
for (int i = 1; i < count - n; i++)
{
pMove = pMove->next;
}
if (pMove->next != NULL)
{
pMove->next = pMove->next->next;
}
}
return temp_head->next;
}
};
int main()
{
Solution solution;
ListNode* ListNode1 = new ListNode(1);
ListNode* ListNode2 = new ListNode(2);
ListNode* ListNode3 = new ListNode(3);
ListNode* ListNode4 = new ListNode(4);
ListNode* ListNode5 = new ListNode(5);
ListNode1->next = ListNode2;
ListNode2->next = ListNode3;
ListNode3->next = ListNode4;
ListNode4->next = ListNode5;
ListNode5->next = NULL;
ListNode* res = solution.removeNthFromEnd(ListNode1,5);
while (res)
{
cout << res->val << endl;
res = res->next;
}
system("pause");
return 0;
}