1. 程式人生 > 實用技巧 >.NetCore之介面快取

.NetCore之介面快取

輸入一個連結串列,輸出該連結串列中倒數第k個節點。為了符合大多數人的習慣,本題從1開始計數,即連結串列的尾節點是倒數第1個節點。

例如,一個連結串列有6個節點,從頭節點開始,它們的值依次是1、2、3、4、5、6。這個連結串列的倒數第3個節點是值為4的節點。

示例:

給定一個連結串列: 1->2->3->4->5, 和 k = 2.

返回連結串列 4->5.

方法一:兩次遍歷

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}


public class Solution { public static void main(String[] args) { ListNode head = new ListNode(2); Solution solution = new Solution(); ListNode kthFromEnd = solution.getKthFromEnd(head, 1); System.out.println(kthFromEnd.val); } public ListNode getKthFromEnd(ListNode head, int
k) { int Len = 0; ListNode point = head; while (point != null) { Len += 1; point = point.next; } point = head; System.out.println("Len:" + Len); for (int i = 0; i < Len - k; i++) { point = point.next; }
return point; } }

方法二:雙指標法

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}


public class Solution {

    public static void main(String[] args) {
        ListNode head = new ListNode(2);
        Solution solution = new Solution();
        ListNode kthFromEnd = solution.getKthFromEnd(head, 1);
        System.out.println(kthFromEnd.val);
    }

public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode start = head, end = head;
        for (int i = 0; i < k; i++) {
            end = end.next;
        }
        while (end != null) {
            end = end.next;
            start = start.next;
        }
        return start;
    }


}