1. 程式人生 > >連結串列---找出單鏈表中倒數第k個節點

連結串列---找出單鏈表中倒數第k個節點

思路:

1、迭代,二指標,快的先走n步,然後一起走,當fast走到最後,slow就是結果

2、遞迴,到達連結串列末尾返回一個0計數器,當計數器等於k時就是第k個

迭代
ListNode nthToLast(ListNode head, int n) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && n > 0) {
            fast=fast.next;
            n--;
        }
        while (fast != null) {//不是if
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

遞迴
public static int nthtolast(ListNode head,int k) {
        if (head == null) {
            return 0;
        }
        int i = nthtolast(head.next,k) + 1;
        if (i == k) {
            System.out.println(head.val);
        }
        return i;
    }
直接返回節點的值
public static ListNode nthtolast(ListNode head,int k,IntWrapper i) {
        if (head == null) {
            return null;
        }
        ListNode node= nthtolast(head.next,k,i);
        i.value = i.value+1;
        if (i.value == k) {
            return head;
        }
        return node;
    }

class IntWrapper{
    public int value = 0;
}