The sword refers to Offer-question 22 (Java Edition): the k-th last node in the linked list

Reference from: "Sword Pointing Offer - Famous Enterprise Interviewer Talking About Typical Programming Questions"

Question : The k-th last node in a linked list
Input a linked list and output the k-th last node in the linked list. In order to conform to the habits of most people, this question starts counting from 1, that is, the tail node of the linked list is the last node. For example, a linked list has 6 nodes, starting from the head node, their values ​​are 1, 2, 3, 4, 5, 6 in order. The third-to-last node of this linked list is the node with the value 4.

The main idea : using double pointers, the front pointer takes k-1 steps first, and the latter pointer moves from the head node. When the front pointer reaches the end, the latter pointer points to the kth node from the bottom. Among them, pay attention to the special case that the node is empty, or the total number of nodes is less than k.

Key point : double pointer traversal

Time complexity : O(n)

public class FindKthNodeFromTail
{
    public static void main(String[] args)
    {
        int[] data = {1, 2, 3, 4, 5, 7};
        ListNode head = LinkedListData.GenerateDataByArray(data);
        ListNode result = FindKthToTail(head, 3); //4
        System.out.println(result.val);
    }

    public static ListNode FindKthToTail(ListNode head, int k)
    {
        if (head == null || k <= 0) return null;
        ListNode ahead = head;
        //前面的指针先走k-1步
        for (int i = 0; i < k-1; i++)
        {
            if (ahead == null) return null;
            ahead = ahead.next;
        }
        ListNode behind = head;
        //前面的指针到达尾部
        while (ahead.next != null)
        {
            behind = behind.next;
            ahead = ahead.next;
        }
        return behind;
    }
}

class ListNode
{
    int val;
    ListNode next = null;

    ListNode(int val)
    {
        this.val = val;
    }
}

class LinkedListData
{
     /**
     * 根据数组生成链表
     * @param data
     * @return
     */
public static ListNode GenerateDataByArray(int[] data)
    {
        ListNode head = new ListNode(data[0]);
        ListNode currentNode = head;
        for (int i = 1; i < data.length; i++)
        {
            ListNode next = new ListNode(data[i]);
            currentNode.next = next;
            currentNode = next;
        }
        return head;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325951595&siteId=291194637