剑指offer刷题记录14——链表中倒数第k个结点

题目描述

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

想到利用双指针标记头部,移动第二个指针直到距离为k - 1,再同时移动两个指针,当第二个指针指向尾部,第一个指针则指向倒数第k个结点。

解法一:

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head == null || k == 0) {
            return null;
        }
        ListNode end = head;
        while(k - 1 > 0) {
            end = end.next;
            if(end == null) {
                return null;
            }
            k--;
        }
        while(end.next != null) {
            end = end.next;
            head = head.next;
        }
        return head;
    }
}

要注意考虑各种异常情况处理。

运行时间:15ms

占用内存:9680k

当然也可以用栈结构来解决问题↓

解法二:

import java.util.Stack;
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        Stack<ListNode> stack = new Stack<ListNode>();
        if(k == 0) {
            return null;
        }
        int i = 0;
        ListNode temp = head;
        while(temp != null) {
            temp = temp.next;
            i++;
        }
        if(i < k) {
            return null;
        }
        while(head != null) {
            stack.push(head);
            head = head.next;
        }
        while(k != 1) {
            stack.pop();
            k--;
        }
        return stack.pop();
    }
}

运行时间:16ms

占用内存:9712k

猜你喜欢

转载自blog.csdn.net/qq_37684824/article/details/82900683