[LeetCode] Remove Nth Node From End of List
来源:互联网 发布:知乎和百度有什么区别 编辑:程序博客网 时间:2024/06/03 20:06
Remove Nth Node From End of List
写完最长前缀,看了一眼下一个easy,发现是个几行代码的题。so,写了吧。
题目:
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.
Try to do this in one pass.
- 解法:先用一个指针p指向头节点,然后把头节点head移动n次,然后再两个指针一起移动直到head移动到结尾,最后删除p的next就是倒数第n个节点了(p到head的距离为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) { ListNode* pkResult = new ListNode(0); pkResult->next = head;//新建一个节点并把next指向head,方便后面返回. ListNode* p = pkResult; for (; n--; head = head->next);//把head节点移动n次. for (; head; head = head->next, p = p->next);//没移动到尾,就继续往下移动,但这些p也要跟着移动. p->next = p->next->next;//把p的next删除. return pkResult->next; }};
欢迎访问我的github,leetcode持续更新: https://github.com/tsfissure/LeetCode
1 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
- Android开发之创建Fragment
- 以人为本 | 如何保证高质量的软件交付
- swift 设置 navigation左右两侧按钮
- [LeetCode15]3Sum
- TCP/IP协议基本概括+ARP协议详解+DNS协议详解---Linux学习笔记
- [LeetCode] Remove Nth Node From End of List
- swift UITabBarController标签栏控制器
- CX3 使用GPIO来显示MIPI解析结果【新手入门手册】
- request method
- 生产消费者模式
- JS中的Map简单实现
- make iframe responsive and fullscreen iframe(支持iframe自适应,并全屏iframe)
- JS&DOM相关介绍
- 一个简单的字符设备驱动程序和测试程序