19. Remove Nth Node From End of List
来源:互联网 发布:东方财富软件使用方法 编辑:程序博客网 时间:2024/05/30 23:03
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.
分析:加入两个指针,fast和slow;
其中fast走到第n个节点时,slow开始走,这个时候slow和fast相距n;
然后当fast走到尾节点时,slow的下一个节点就是要删除的节点;
接下来做删除操作即可。
/** * 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) return NULL; ListNode *temp=new ListNode(-1); temp->next=head; ListNode* fast=temp,*slow=temp; for(int i=0;i<n;i++) fast=fast->next; while(fast->next) { slow=slow->next; fast=fast->next; } ListNode* delete_node=slow->next; slow->next=slow->next->next; delete delete_node; return temp->next; }};
阅读全文
0 0
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node From End of List
- 数论 高斯消元模板
- 如何使用特定的SSH Key提交GIT
- 欢迎使用CSDN-markdown编辑器
- 企业级后台接口开发。环境基于spring+springboot+springmvc+mybatis。测试 junit4
- 上传图片的格式验证
- 19. Remove Nth Node From End of List
- 用Python实现一个简单的线程池模型效果代码分析讲解
- Linux学习从入门到精通推荐书籍
- html传参与输入页码格式验证
- Apache与CDH的比较
- LintCode67
- PCB绘图,覆铜区域或信号线附近添加几排过孔的作用
- LG G2修复弹出n个未识别磁盘
- 大数据生态系统基础:Hadoop(四):Hadoop 3.0.0 HDFS SHELL 命令