@yexiaoqi 2022-05-20T08:41:28.000000Z 字数 914 阅读 341

# HJ51. 输出单向链表中倒数第k个结点

刷题

struct ListNode{    int m_nKey;    ListNode* m_pNext;};

(1)正序构建链表;
(2)构建后要忘记链表长度。

1. 输入链表结点个数
2. 输入链表的值
3. 输入k的值

输入：8
1 2 3 4 5 6 7 8
4



public class Main {    static class ListNode {        int key;        ListNode next;        public ListNode() {}        public ListNode(int key, ListNode next) {            this.key = key;            this.next = next;        }    }    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        while (sc.hasNext()) {            int n = sc.nextInt();            ListNode head = new ListNode();//增加一个head节点            ListNode node = head;            //正序构建单链表            for (int i=0; i<n; i++) {                node.next = new ListNode(sc.nextInt(), null);                node = node.next;            }            //双指针找倒数第k个节点            ListNode l = head.next;            ListNode r = head.next;            int kk = sc.nextInt();            for (int k = 0; k < kk - 1; k++) {                r = r.next;            }            while (r.next != null) {                l = l.next;                r = r.next;            }            System.out.println(l.key);        }    }}

• 私有
• 公开
• 删除