《剑指offer》第14题——找一个链表的倒数第k个节点

164 阅读1分钟

题目:

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

思路:

用两个指针,pre和tail,移动这两个指针,使得pre和tail的间距是k-1,这两个节点以及它们之间的节点所构成的链表成为一个长度为k+1的“尺子”,移动这把尺子使得tail移动到最后一个节点,那么pre所指就是倒数第k个。

另外,写main函数的时候还需添加arrayToList()方法使得数组变成链表。

Java

package nowcoder;

public class S14_FindKthToTail {
    public ListNode findKthToTail(ListNode head, int k) {
        ListNode pre = head;
        ListNode last = head;
        if(head==null || k <=0)
            return null;
        for(int i=0;i <k-1;i++){ //使得pre和last的间距为k-1
            if(last.next!=null){
                last = last.next;
            }
            else
                return null;
        }
        while(last.next!=null){ //pre和last的间距为k-1,当last移动到最后一个节点时,pre就是倒数第k个
            pre = pre.next;
            last = last.next;
        }
        return pre;
    }
    public ListNode arrayToList(int[] array, int index){
        ListNode head = null;
        if (index < array.length){
            int value = array[index];
            head = new ListNode(value);
            head.next = arrayToList(array, index+1);
        }
        return head;
    }
    public static void main(String[] args){
        S14_FindKthToTail s14 = new S14_FindKthToTail();
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8};
        ListNode head = s14.arrayToList(array, 0);
        ListNode result = s14.findKthToTail(head, 3);
        if (result == null)
            System.out.print("null");
        else
            System.out.print(result.val);
    }
}

Python

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class FindKthToTail:
    def findKthToTail(self, head, k):
        tail = pre = head
        for _ in range(k):
            if not tail:
                return None
            tail = tail.next
        while tail:
            pre = pre.next
            tail = tail.next
        return pre
    def arrayToList(self, array, index):
        head = None
        if index < len(array):
            value = array[index]
            head = ListNode(value)
            head.next = self.arrayToList(array, index+1)
        return head

if __name__ == '__main__':
    test = FindKthToTail()
    array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    head = test.arrayToList(array, 0)
    result = test.findKthToTail(head, 11)
    if result:
        print(result.val)
    else:print("null")