链表倒数第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