[LeetCode] Remove Nth Node From End of List

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.

依然是双指针思想,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针就是要删除的节点。

复制代码
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *removeNthFromEnd(ListNode *head, int n) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if (head == NULL)
15             return NULL;
16             
17         ListNode *pPre = NULL;
18         ListNode *p = head;
19         ListNode *q = head;
20         for(int i = 0; i < n - 1; i++)
21             q = q->next;
22             
23         while(q->next)
24         {
25             pPre = p;
26             p = p->next;
27             q = q->next;
28         }
29         
30         if (pPre == NULL)
31         {
32             head = p->next;
33             delete p;
34         }
35         else
36         {
37             pPre->next = p->next;
38             delete p;
39         }
40         
41         return head;
42     }
43 };
复制代码
posted @   chkkch  阅读(8339)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示