算法

剑指 Offer 22. 链表中倒数第k个节点

2021-03-13  本文已影响0人  秃头哥编程

题目链接:https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        int len = 0;
        ListNode temp = head;
        while (temp != null) {
            len++;
            temp = temp.next;
        }
        
        temp = head;
        int index = len - k;
        while (index-- > 0) {
            temp = temp.next;
        }

        return temp;
    }
}
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode frontNode = head, behindNode = head;

        // 先走k个节点,剩下就还有len - k个节点
        while (k-- > 0) {
            frontNode = frontNode.next;
        }

        // 这里其实就是移动len - k个节点,刚好是倒数第K个节点
        while (frontNode != null) {
            frontNode = frontNode.next;
            behindNode = behindNode.next;
        }

        return behindNode;
    }
}

但两种题解执行结果好像并没有什么差别。


image.png
上一篇 下一篇

猜你喜欢

热点阅读