LeetCode问题解答:19. Remove Nth Node From End of List
来源:互联网 发布:js push json 编辑:程序博客网 时间:2024/05/29 13:43
难度:Medium
源链接: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.
Note:
Given n will always be valid.
Try to do this in one pass.
思考与解答:
该题需要在一个单向链表上移除倒数第N个节点,同时对效率做出了要求,需要一趟完成,也就是不要把整个链表扫一遍知道节点数量后
再从头去数到第N个节点。
对于这道题,需要3个指针来进行,首先用两个指针确定一个区间,大小为n,我们让这个区间在整个链表上移动,最终区间尾到底时,头
部正好就落在倒数第N位,同时为了链接去掉一个节点的链表,需要多余的一个指针来记住倒数第N个节点的前一个节点的地址。
要注意的是,需要对倒数第N个节点的前一个节点进行分类,因为它可能根本不存在。
具体代码:
class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* lastn = NULL; ListNode* nth = head; ListNode* p = head; for (int i = 0; i < n-1; i++) { p = p->next; } while (p->next != NULL){ lastn = nth; p = p->next; nth = nth->next; } if (lastn != NULL) { lastn->next = nth->next; return head; } else { return nth->next; } }};
阅读全文
0 0
- LeetCode问题解答:19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [LeetCode]19.Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List Leetcode Python
- LeetCode --- 19. Remove Nth Node From End of List
- LeetCode 19.Remove Nth Node From End of List
- [Leetcode] 19. Remove Nth Node From End of List
- [leetcode] 19.Remove Nth Node From End of List
- <LeetCode OJ> 19. Remove Nth Node From End of List
- 19. Remove Nth Node From End of List LeetCode
- leetcode 19. Remove Nth Node From End of List
- [LeetCode OJ] 19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- Leetcode:19. Remove Nth Node From End of List(JAVA)
- leetcode 19. Remove Nth Node From End of List
- Leetcode 19. Remove Nth Node From End of List
- 【LeetCode】19. Remove Nth Node From End of List
- 项目开发性能优化注意事项
- Java基础知识
- 查找字段在数据库中的那个表 mysql
- HashMap的实现
- AngualrJs 最新 文件图片上传教程5:Client-css Client-config
- LeetCode问题解答:19. Remove Nth Node From End of List
- Unity资源加载以及释放
- 强制横屏或竖屏
- ndroid中View.inflate()
- Java面向对象(四)final关键字
- Linux+C+动态库(*.so文件)
- DbComparisonExpression需要具有可比较类型的参数。
- Ajax接收Java服务端发送的text数据(用户名检查)
- @Column 大小写