LintCode_166_链表倒数第n个节点
来源:互联网 发布:cf卡数据恢复 编辑:程序博客网 时间:2024/04/28 04:15
找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
两个节点中间差n-1个节点,两个一起向后推进,直到后面那个节点的下一个为null,返回前一个就可以了。很简单,注意判断head为空就OK。
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The first node of linked list. * @param n: An integer. * @return: Nth to last node of a singly linked list. */ ListNode nthToLast(ListNode head, int n) { // write your code here if(head == null){ return null; } ListNode cur = head; ListNode n_last = head; for(int i = 0 ; i < n - 1 ; i++){ n_last = n_last.next; } while(n_last.next != null){ cur = cur.next; n_last = n_last.next; } return cur; }}
0 0
- LintCode_166_链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 链表倒数第n个节点
- 输出链表倒数第n个节点数据
- SQL语句操作优先级顺序
- SecureCRT突然假死的问题(Ctrl+S)
- Spring MVC中的DispatcherServlet学习
- 使用AJAX异步提交表单的几种方式
- 无密码身份验证:安全、简单且部署快速
- LintCode_166_链表倒数第n个节点
- http protocol
- rman 恢复目录的使用
- KVC中setValuesForKeysWithDictionary:
- bootstrap-fileInput
- qml中使用多点触摸
- ios 日历 NSCalendar
- 对任意随即10个数求和(4)
- 作业作业作业