`

链表倒数第n个节点

阅读更多

题意:

找到单链表倒数第n个节点,保证链表中节点的最少数量为n。

 

解法:我们看到这个问题首先要考虑的就是边界情况,指针是否为空?n是否为0?n是否 大于链表的长度?

          边界定义好,我们就开始写代码了,定义两个指针,第一个指针走到n的时候,第二个指针开始行走,当第一个指针走到指针尾部的时候,返回第二个指针所指向的节点。

 

题目地址

 

代码如下:

/**
 * 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. 
     */
    public ListNode nthToLast(ListNode head, int n) {
        // write your code here
        if(head == null||n==0){
            return null;
        }
        ListNode node1 = head;
        for(int i = 0 ; i < n-1 ; i++){
            if(node1.next!=null){
                node1 = node1.next;
            }else{
                return null;
            }
        }
        ListNode node2 = head;
        while(node1.next!=null){
            node1 = node1.next;
            node2 = node2.next;
        }
        return node2;
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics