leetcode:Remove Nth Node From End of List
来源:互联网 发布:java park wait 区别 编辑:程序博客网 时间:2024/05/24 02:25
一、 题目
给定一个单链表,删除倒数第n个节点,返回删除了的链表。
例如: 已知: 1->2->3->4->5, n = 2.
处理后:1->2->3->5.
试着遍历一次完成。
二、 分析
看到这道题我第一感觉就是双指针,因为要删除倒数第n个数,所以两个指针的间距也就是这个n,当右边的指针到达末尾处时,那么左指针的下一个指针就是要删除的节点。其实会有下面几种特殊情况:
1、{1,2},n=1;
2、{1,2},n=2;
3、{},0
当然,有人可能会说n可不可以大于节点数,不过这个题目已经限制了n是有效的。
扩展:1、n的值不限制
2、链表不限于单链表,求删除离头节点倒数n个
/** * Definition for singly-linked list. * 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||head->next==NULL) return NULL; ListNode *Rnode = head; ListNode *Lnode = head; for(int i=1; i<=n; i++){ Rnode = Rnode->next; } if(Rnode==NULL){ head = head->next; return head; } while(Rnode->next!=NULL){ Lnode = Lnode->next; Rnode = Rnode->next; } Lnode->next = Lnode->next->next; return head; }};
0 0
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- LeetCode | Remove Nth Node From End of List
- leetcode之Remove Nth Node From End of List
- Apache Maven入门实例以及了解maven的核心概念
- [大规模并行处理器编程实战]读书笔记_Heterogeneous Parallel Programming_CHAPTER_03
- C++:静态成员函数,静态数据成员,成员函数存储方式
- Java Serializable(序列化)的总结
- BZOJ 1057 ZJOI 2007 棋盘制作 DP+悬线法
- leetcode:Remove Nth Node From End of List
- django - 多数据库及分库实现
- 占位
- 占位
- 占位
- 占位
- 占位
- 从CommonJS vs AMD中解读JavaScript依赖管理
- 占位