19. Remove Nth Node From End of List Medium
来源:互联网 发布:python 二叉树遍历 编辑:程序博客网 时间:2024/05/29 02:20
这道题是关于单链表的应用,第一次在leetcode上做链表的题,当作复习了~
题目中好像提示了尽量一次遍历,可以用两个指针,我为了方便用了三个指针。主要做法就是删除倒数第n个节点的话,可以让一个指针先指到从前往后数第n个,然后用另一个指针从head开始,两个指针同时往后移动,知道前面那个指针指到null,那后一个指针指向的就是要删除的节点,但是如果你要删除,必须从待删节点的前一个节点入手,为了时间更短,我加入了一个parent指针,记录后一个指针的父节点。
用两个指针的话也可以,我写的是9ms的,这里贴出三个指针,6ms的版本:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == NULL)return NULL;
ListNode * front = head;
ListNode * back = head;
ListNode * parent = back;
while(n--){
front = front->next;
}
while(front != NULL){
front = front->next;
parent = back;
back = back->next;
}
if(parent == back){head = head->next; return head;}
parent->next = parent->next->next;
return head;
}
};
- 19. Remove Nth Node From End of List Medium
- 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
- 垂直同步(VSYNC)实现原理
- 递归递推练习 -b 王小二切饼/HDU折线分割平面
- Java集合之LinkedList总结
- 拖拽布局
- java——设置sa账号密码,jdbc连接sqlserver2005数据库
- 19. Remove Nth Node From End of List Medium
- DS.Lab筆記
- Linux命令大全(六)--Linux文件系统
- Android显示具体位置地图
- 数据的交换输出
- [LeetCode] Intersection of Two Arrays 两个数组的交集
- $.ajax()方法详解
- 1004. 成绩排名 (20)(Java实现)
- 操作符和表达式的总结