第二十周_A-链表的倒数第 k 个节点

46 阅读1分钟

单链表的倒数第k个节点。力扣-简单-链表

  1. 自定义了链表结构
  2. 打印链表函数

题解:

使用快慢指针解决:快指针先走 k 步,然后快慢一起走。当快的走完了,此时慢的就是倒数的第 k 步

public class 链表的倒数第k个节点 {
    public static void main(String[] args) {
        // 模拟一个链表
        ListNode head = new ListNode(1);
        ListNode listNode1 = new ListNode(2);
        head.next = listNode1;
        ListNode listNode2 = new ListNode(3);
        listNode1.next = listNode2;
        ListNode listNode3 = new ListNode(4);
        listNode2.next = listNode3;
        ListNode listNode4 = new ListNode(5);
        listNode3.next = listNode4;
        ListNode listNode5 = new ListNode(6);
        listNode4.next = listNode5;

        //打印链表
        printListNode(head);

        ListNode resultListNode = getKthFromEnd(head, 2);
        printListNode(resultListNode);

    }

    /**
* 快慢指针:快指针先走 k 步,然后快慢一起走。当快的走完了,此时慢的就是倒数的第 k 步
*
* @param head  头节点
* @param
* @return
*/
    public static ListNode getKthFromEnd(ListNode head, int k) {
        ListNode forntNode = head, endNode = head;
        while (forntNode != null && k > 0) {
            forntNode = forntNode.next;
            k--;
        }
        while (forntNode != null) {
            forntNode = forntNode.next;
            endNode = endNode.next;
        }
        return endNode;
    }

    public static class ListNode {
        int val;
        ListNode next;

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

    public static void printListNode(ListNode head) {

        while (head.next != null) {
            System.out.print(head.val + "->");
            head = head.next;
        }
        System.out.println(head.val + "->" + null);
    }

}