[LeetCode-Algorithms-19] "Remove Nth Node From End of List" (2017.11.16-WEEK11)
来源:互联网 发布:修改图片软件 编辑:程序博客网 时间:2024/06/05 04:11
题目链接: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
, andn = 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.
(1)思路:注意只能进行一次遍历就得出结果。那么可以使用两个指针始终保持n距离,当一个指针移动到链表尾部时,另外一个指针指向要删除元素的前一个,那么删除它的下一个节点。
(2)代码:
/** * 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->next==NULL) return NULL; ListNode *p = head, *q = head; while(n--) q = q->next; if (q == NULL) return head->next; while(q->next) { q = q->next; p = p->next; } p->next = p->next->next; return head; }};
(3)提交结果:
阅读全文
0 0
- [LeetCode-Algorithms-19] "Remove Nth Node From End of List" (2017.11.16-WEEK11)
- LeetCode Algorithms 19. Remove Nth Node From End of List
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- Algorithms—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, Easy] 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 Solutions
- 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 | #19 Remove Nth Node From End of List
- leetcode.19----------Remove Nth Node From End of List
- [Leetcode 19, Easy] 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
- 存储过程与函数
- ionic3使用随笔
- implict declaration
- VS2013怎么配置opencv才能不用每次都重新配置一遍?
- 数据库拆分字段('1,2')--('1','2')
- [LeetCode-Algorithms-19] "Remove Nth Node From End of List" (2017.11.16-WEEK11)
- Ubuntu16.04 修改网卡名称为wlan0/eth0
- tomcat启动项目出现Could not publish server configuration for Tomcat v7.0 Server at localhost
- 编译裁减代码的几点体会
- 2017第二十三届中国国际家具展览会会刊(参展商名录)
- 记一个网络请求头部设置问题
- Linux下修改profile后用户无法登陆的问题
- 伊朗央行银行家:“危险的”比特币需要审查
- Caffe 中怎样准备训练数据