Leetcode(16)
来源:互联网 发布:tcp ip网络编程 源码 编辑:程序博客网 时间:2024/05/19 02:19
https://leetcode.com/problems/remove-nth-node-from-end-of-list/#/description
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.
Solution:
用两个指针来处理问题,一个指针先移动n位,一个指针指向Head,然后一起移动,当前指针为空时,删除后指针指向的Node。
ListNode* RemoveNthFromEnd::removeNthFromEnd(ListNode *head, int n) { if(head == nullptr || n == 0) { return nullptr; } ListNode* pAhead = head; for(unsigned int i = 0; i < n - 1; ++i) { if(pAhead ->m_pNext != nullptr) { pAhead = pAhead -> m_pNext; } else { return head; } } ListNode** pBehind = &head; while (pAhead -> m_pNext != nullptr) { pAhead = pAhead -> m_pNext; pBehind = &((*pBehind) -> m_pNext); } *pBehind = (*pBehind) -> m_pNext; return head;}
阅读全文
0 0
- Leetcode 16
- Leetcode(16)
- LeetCode 16
- leetcode note--leetcode 16 3Sum Closest
- LeetCode 16 Single Number
- [leetcode]16 Valid Palindrome
- 【LeetCode】16_3Sum Closest
- LeetCode 16_3Sum Closest
- Leetcode no. 16
- leetcode #16 in cpp
- leetCode练习(16)
- 【LeetCode 16】 threeSumClosest
- (java)leetcode-16
- LEETCODE 15&&16
- LeetCode 16 Jump Game
- Leetcode双指针16
- [Leetcode] 128, 16, 18
- leetcode 16 threeSumClosest
- Java 21:Spring 4(Intelij IDEA下的SpringMVC环境搭建)
- List中的set方法和add方法, 以及排序操作
- js加载
- I/O多路转接之poll
- 百度地图API示例之添加/删除工具条、比例尺控件
- Leetcode(16)
- WebView性能、体验分析与优化
- 开博客之初心
- 和菜鸟一起学电子小玩意之四轴飞行器原理
- 设计模式---访问者模式
- PuTTY (3) Serial port connection
- Visual Studio Code 让高效进行到底
- php多语言包
- (鸿洋)Android 6.0 运行时权限处理完全解析