166.Nth to Last Node in List-链表倒数第n个节点(容易题)
来源:互联网 发布:mysql分类汇总 编辑:程序博客网 时间:2024/05/01 13:37
链表倒数第n个节点
题目
找到单链表倒数第n个节点,保证链表中节点的最少数量为n。
样例
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.
题解
定义指针gap_n指向head,并向后移动n项,再与head指针同时后移直至gap_n为null,此时head指针指向的节点就是答案。
/** * 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) { ListNode gap_n = head; while (n-- > 0) { gap_n = gap_n.next; } while (gap_n != null) { head= head.next; gap_n = gap_n.next; } return result; }}
Last Update 2016.9.7
0 0
- 166.Nth to Last Node in List-链表倒数第n个节点(容易题)
- LintCode Nth to Last Node in List 链表倒数第n个节点
- LintCode | Easy | 链表倒数第n个节点 | Nth to Last Node in List
- 174.Remove Nth Node From End of List-删除链表中倒数第n个节点(容易题)
- leetcode:Remove Nth Node From End of List(删除链表倒数第n个节点)【面试算法题】
- LeetCode(Remove Nth Node From End of List)删除链表倒数第n个节点
- Remove Nth Node From End of List 删除链表倒数第N个节点
- #19 Remove Nth Node From End of List(删除链表倒数第N个节点)
- 19. Remove Nth Node From End of List (移除链表倒数第n个节点)
- 19. Remove Nth Node From End of List(移除链表的倒数第n个节点)
- LeetCode--Remove Nth Node From End of List(移除链表的倒数第N个节点)Python
- [LeetCode-19] Remove Nth Node From End of List(删除倒数第N个节点)
- [LeetCode]—Remove Nth Node From End of List 删除链表的倒数第n个节点
- leetcode 3. 移除链表的倒数第n个节点 Remove Nth Node From End of List
- 【Leetcode】19. Remove Nth Node From End of List - 删掉链表倒数第n个节点
- leetcode-19. Remove Nth Node From End of List(删除链表倒数第N个节点)
- LeetCode 19 Remove Nth Node From End of List 移除倒数第N个节点
- LintCode Remove Nth Node From End of List 删除链表中倒数第n个节点
- EventBus的源码分析
- 口语语言理解
- ffmpeg代码笔记3:获取MP4视频流的帧率
- user agent stylesheet 处理
- 问题:Hibernate的自动补全属性功能
- 166.Nth to Last Node in List-链表倒数第n个节点(容易题)
- 如何使用MongoDB自带的json库来反序列json字符串
- Winmanager,NERDTree和MiniBufExplorer
- WOJ1017-Billiard Ball
- Android 软键盘弹出时布局内指定内容上移实现及问题解决
- stm32f103使用TIM1和TIM2输出PWM
- SpringMVC+mybatis中实体类字段名与数据库字段名不匹配问题
- epoll 的accept , read, write(重要)
- GenerateParenthes——22