【剑指offer】链表中的倒数第k个节点

题目描述

输入一个链表,输出该链表中倒数第k个结点。

举一个简单的例子,比如链表{1,2,3,4,5},如果要返回倒数第二个节点,也就是k=2,就相当于正数第5-k+1=4个节点,所以我们可以采用两次循环:一次循环得到链表的结点个数;另一次循环则是从链表中找到第n-k+1个节点。虽然是两次循环,但时间复杂度是 O(n)

,需要注意的是,这里仍然需要对链表的边界条件进行判断

package com.gpl.offer.jianzhi;

/**
 * Created by gpl on 2016/8/9.
 */
public class KthToTail {     //链表中的倒数第k个节点

    public LinkNode findk(LinkNode head,int k){
        if(head == null || k < 0)
            return null;
        LinkNode front  = head;
        LinkNode behind = null;
        for(int i=0;i<k-1;i++){
            if(front.next!=null)
                front = front.next;
            else
                return null;
        }
        behind = head;
        while(front.next!=null){
            front = front.next;
            behind = behind.next;
        }
        return behind;

    }

    public static void main(String[] args){
        LinkNode head = new LinkNode(1);
        LinkNode h1 = new LinkNode(2);
        LinkNode h2 = new LinkNode(3);
        LinkNode h3 = new LinkNode(4);
        LinkNode h4 = new LinkNode(5);
        LinkNode h5 = new LinkNode(6);
        head.setNext(h1);
        h1.setNext(h2);
        h2.setNext(h3);
        h3.setNext(h4);
        h4.setNext(h5);
        h5.setNext(null);
        KthToTail ktt = new KthToTail();
        LinkNode nodeK = ktt.findk(head,6);
        System.out.println(nodeK.val);




    }
}

class LinkNode{
    int val;
    LinkNode next;
    public LinkNode(int val){
        this.val = val;
    }
    public void setNext(LinkNode next) {
        this.next = next;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值