[leetcode 19 Remove Nth Node From End of List]week 13
来源:互联网 发布:黄金利多利空数据软件 编辑:程序博客网 时间:2024/06/05 04:44
一、题目
Given a linked list, remove the nth nodefrom 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 willalways be valid. Try to do this in one pass.
二、代码
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode * first = head;
ListNode * second = head;
for(int i = 0;i < n;i++)
first = first->next;
if(first == NULL)
return head->next;
while(first->next)
{
first = first->next;
second = second->next;
}
second->next = second->next->next;
return head;
}
};
三、思路
由于是移除从尾端数的第N个节点,设立两个指针,先让第一个指针移动n步,再同步移动知道第一个指针到达末尾已到达定位末端第N个节点的效果。若第一个指针移动n步后为空,则说明n>=链表长度,所以移除head即可返回head->next。若非空,则待定位成功后将第二个指针再移动一步。
- [leetcode 19 Remove Nth Node From End of List]week 13
- [Leetcode]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 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
- leetCode #19 Remove Nth Node From End of List
- leetcode 19 Remove Nth Node From End of List
- [leetcode 204. Count Primes]week 3
- [leetcode 104. Maximum Depth of Binary Tree]week 5
- 80端口被占用 PID 4
- [leetcode 55. Jump Game]week 7
- [leetcode 50. Pow(x, n)]week 11
- [leetcode 19 Remove Nth Node From End of List]week 13
- 两类strling数
- [leetcode Merge Two Sorted Lists]week 15
- [leetcode Search Insert Position]week 17
- Linux(redhat6.5)下 安装mysql5.7.18——yum方式
- [leetcode Best Time to Buy and Sell Stock]week 18
- [leetcode Maximum Subarray]week 19
- 线性表(List)---顺序存储结构
- [算法概论 8.12 k-生成树问题]