链表中倒数第K个结点

来源:互联网 发布:windows入门教程 编辑:程序博客网 时间:2024/06/05 16:09

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

思考:两个指针,第一个走K-1步,第二个从头开始
两个一起走,第二个走到尾部时,第一个指针指向的就是倒数第k个结点。
需要注意输入的特殊情况。

/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/public class Solution {    public ListNode FindKthToTail(ListNode head,int k) {        //链表为空或者倒数结点是负数,返回null        if(head == null || k <= 0)            return null;        ListNode first = head;        ListNode second = head;        //第一个指针先移动到倒数第k-1个结点        int count = k - 1;        while(first != null && count != 0){            first = first.next;            count--;        }        //如果倒数的长度大于链表长度,直接返回        if(first == null)            return null;        //遍历找到倒数第k个结点        while(first.next != null){            second = second.next;            first = first.next;        }        return second;    }}