剑指Offer:链表中倒数第k个结点(java代码实现)

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

解题思路
思路很简单
1.
遍历链表的同时 k–
遍历完链表如果k0说明找的就是第一个结点
如果小于0 进行第二步
2.遍历链表的同时k++
当k
0时找到该结点

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head == null || k == 0) {
            return null;
        }
        ListNode temp = head;
        ListNode res = null;
         
        while(temp != null) {
            k--;
            temp = temp.next;
        }       
        if(k == 0){
            res = head;
        }else if(k < 0) {
            temp = head;
            while(++k != 0) {
                temp = temp.next;
            }
            res = temp.next;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/wmh1152151276/article/details/88171777