3个Java链表面试题:翻转,取中间,取倒数第k个

it2025-05-05  11

1、反转单链表:

public Node reverseList(){ Node pre = null; Node newHead = null; Node cur = this.head; while (cur != null){ Node cueNext = cur.next; if (cueNext == null) { newHead = cur; } cur.next = pre; pre = cur; cur = cueNext; } return newHead; }

2、给定一个带有头结点 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结

点。 public Node middleNode(){ Node fast = this.head; Node slow = this.head; while (fast != null && fast.next != null){ fast = fast.next.next; slow = slow.next; } return slow;

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

public Node FindKthToTail(int k){ Node fast = this.head; Node slow = this.head; if(k < 0 || head == null){ System.out.println("k的位置不合法"); return null; } while (k-1 > 0) { if (fast.next != null) { fast = fast.next; k--; } else { System.out.println("没有k这个位置"); return null; } } while (fast.next != null){ fast = fast.next; slow = slow.next; } return slow; }

 

最新回复(0)