LeetCode题解(19)--Remove Nth Node From End of List
2024-08-22 21:51:30
https://leetcode.com/problems/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, 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.
思路:
考察指针的灵活使用。使用两个指针a和b就够了,中间间隔n个,一起向前移动,直到最后一个节点,然后删掉a->next。这样的算法需要注意删掉的是第一个节点的情况(也即不能是a->next了,直接head=head->next)。
我的AC代码:
/**
* 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 * to_remove, * p;
p=head;
for(int i=;i<n;i++){
p=p->next;
}
if(p==NULL){
head=head->next;
return head;
}
to_remove=head;
while(p->next!=NULL){
p=p->next;
to_remove=to_remove->next;
}
to_remove->next=to_remove->next->next;
return head;
}
};
最新文章
- 我的ES6学习之路(一)
- git和nginx安装
- is not in the sudoers file 问题解决【转载】
- Douglas Crockford: entityify &; deentityify
- c++ 遍历ini
- MyBatis学习总结4--解决字段名与实体类属性名不相同的冲突
- 团体程序设计天梯赛-练习集L1-008. 求整数段和
- xilinx仿真库的作用(原创)
- XDocument读取xml的所有元素以及XPath语法
- linux杂记(?)命令别名——alias
- Spring 类构造器初始化实例
- robot framework 使用四:分层设计和截图以及注意事项
- Git学习篇之git remote add origin错误
- JAVA基础知识总结:十八
- ubuntu 16.04 下安装smplayer视频播放器
- python 基础_ 打印输出 循环分支2
- 【基础知识】.Net基础加强 第四天
- mysql使用笔记(一)
- Linux系统——磁盘管理
- labview在编写程序框图中遇到的一些布尔按钮控制布尔指示灯问题
热门文章
- 【LeetCode】Palindrome Number(回文数)
- python3--__repr_和__str__会返回字符串表达形式
- Windows同步阿里云时间
- Opencv学习笔记——视频进度条的随动
- HDU 5833 Zhu and 772002 ——线性基
- P1279 字串距离 (动态规划)
- 【2018.9.26】K-D Tree详解
- android开发里跳过的坑——camera调用setDisplayOrientation设置预览显示旋转无效
- Yii 之视图数据块
- golang sort包 排序