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;
}
};

最新文章

  1. 我的ES6学习之路(一)
  2. git和nginx安装
  3. is not in the sudoers file 问题解决【转载】
  4. Douglas Crockford: entityify &amp; deentityify
  5. c++ 遍历ini
  6. MyBatis学习总结4--解决字段名与实体类属性名不相同的冲突
  7. 团体程序设计天梯赛-练习集L1-008. 求整数段和
  8. xilinx仿真库的作用(原创)
  9. XDocument读取xml的所有元素以及XPath语法
  10. linux杂记(?)命令别名——alias
  11. Spring 类构造器初始化实例
  12. robot framework 使用四:分层设计和截图以及注意事项
  13. Git学习篇之git remote add origin错误
  14. JAVA基础知识总结:十八
  15. ubuntu 16.04 下安装smplayer视频播放器
  16. python 基础_ 打印输出 循环分支2
  17. 【基础知识】.Net基础加强 第四天
  18. mysql使用笔记(一)
  19. Linux系统——磁盘管理
  20. labview在编写程序框图中遇到的一些布尔按钮控制布尔指示灯问题

热门文章

  1. 【LeetCode】Palindrome Number(回文数)
  2. python3--__repr_和__str__会返回字符串表达形式
  3. Windows同步阿里云时间
  4. Opencv学习笔记——视频进度条的随动
  5. HDU 5833 Zhu and 772002 ——线性基
  6. P1279 字串距离 (动态规划)
  7. 【2018.9.26】K-D Tree详解
  8. android开发里跳过的坑——camera调用setDisplayOrientation设置预览显示旋转无效
  9. Yii 之视图数据块
  10. golang sort包 排序