建设网站需要哪些经营范围lnmp wordpress建设多网站
链表_删除链表的倒数第N个节点
- 一、leetcode-19
- 二、题解
- 1.引库
- 2.代码
一、leetcode-19
删除链表的倒数第N个节点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
二、题解
1.引库
#include <iostream>#include <cstdio>#include <cstdlib>#include <queue>#include <stack>#include <algorithm>#include <string>#include <map>#include <set>#include <vector>using namespace std;
2.代码
/*** 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 *newhead=new ListNode(0),*fast=newhead,*slow=newhead;newhead->next=head;for(int i=0;i<=n;i++) fast=fast->next;while(fast!=NULL) fast=fast->next,slow=slow->next;ListNode *tmp=slow->next;slow->next=slow->next->next;delete tmp;return newhead->next;}
};