FTPrep, 19 Remove Nth Node From End of List
来源:互联网 发布:大话设计模式 php pdf 编辑:程序博客网 时间:2024/06/07 10:06
老题一道,拿到手有点生疏,把思路理清了,一次写完,非常爽。只有一个小bug,在用listNode的constructor的时候,没有传入一个参数。。真正面试时没有看清class的interface会吃亏的的。。
思路:把这个n想成是 尾巴的起头,平时说倒数1个,那么尾巴长度就是1,最后一个node就是这个尾巴的起头。倒数第二个,那么尾巴长度就是2,倒数第二个就是这个长度为2的尾巴的头。所以是n的话就是,找到长度为n的尾巴的头。
所以重要的关键点就是,确定好这个尾巴,因为长度是固定的,可以把它想成一个固定的整体。
有了这个整体后,那么就挨个后移,直到尾巴的最后一个node,走到了list的最后一个node,那就可以终止了,即找到了倒数n-th这个node,也就是这个尾巴的头一个node。
代码如下,两个循环:
1,用尾巴的固定长度找到尾巴的最后一个node;
2,尾巴整体后移,用最后一个node 的next==null,作为判断条件,出while循环时就算找到了倒数n-th的node
3,最后做一个简单的链接即可。
这个加起来就one pass,时间复杂度就是N
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(n<=0) return head; ListNode dummy = new ListNode(0); ListNode tail = dummy; dummy.next=head; for(int i=1; i<=n; i++){ if(tail.next==null) return head; tail=tail.next; } ListNode prev = dummy; while(tail.next!=null){ tail=tail.next; prev=prev.next; } prev.next=prev.next.next; return dummy.next; }}
阅读全文
0 0
- FTPrep, 19 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
- JS和OC交互
- Hive2.0 函数大全(中文版)
- CCNA学习笔记1——OSI参考模型
- C# override和new的区别 (修饰函数时)
- 使用Drawable定义一个虚线或虚线矩形框
- FTPrep, 19 Remove Nth Node From End of List
- HTML基础和JSP了解及JSP中代码加载顺序
- intelliJ Idea自带热部署和Jrebel实现热部署
- Joda-Time的使用
- 一个经典例子让你彻彻底底理解java回调机制
- Java中的ReentrantLock和synchronized两种锁定机制的对比
- Coursera Algorithms week1 Interview Questions: 3Sum in quadratic time
- opensips 服务器搭建测试
- mysql数据库连接池dbcp与c3p0对比