📅  最后修改于: 2023-12-03 14:56:19.371000             🧑  作者: Mango
在链表中找到倒数第N个节点是一种常见的问题。本文将介绍如何使用Java编写一个程序来解决这个问题。
给定一个单链表,要求找到链表中倒数第N个节点,并将该节点的值打印出来。
我们可以使用两个指针来解决这个问题。首先,我们定义两个指针p和q并将它们都指向链表的头节点。接下来,我们将指针q向前移动N个位置。此时,指针p和指针q之间的距离为N个节点。然后,我们同时移动指针p和指针q,直到指针q到达链表的末尾。此时,指针p就指向了倒数第N个节点。
以下是Java程序的实现:
public class LinkedListUtil {
public static void printNthNodeFromEnd(Node head, int n) {
if (head == null || n <= 0) {
System.out.println("Invalid input");
return;
}
Node p = head;
Node q = head;
// Move q n positions ahead
for (int i = 0; i < n; i++) {
if (q == null) {
System.out.println("Invalid input");
return;
}
q = q.next;
}
// Move p and q together until q reaches the end
while (q != null) {
p = p.next;
q = q.next;
}
System.out.println("Value of the nth node from end: " + p.data);
}
public static void main(String[] args) {
// Create a sample linked list
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
// Print the value of the 2nd node from the end
printNthNodeFromEnd(head, 2);
}
}
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
上述程序中,LinkedListUtil
类包含各种链表相关的实用方法。printNthNodeFromEnd
方法用于从链表末尾打印第N个节点的值。在main
方法中,我们创建了一个简单的链表,并调用printNthNodeFromEnd
方法来打印倒数第2个节点的值。
上述程序的运行结果如下:
Value of the nth node from end: 4
该结果表示链表中倒数第2个节点的值为4。
通过使用两个指针,我们可以高效地找到链表中倒数第N个节点。这个问题在面试中是常见的,因此掌握这种解决方案对程序员来说是很有帮助的。以上提供的Java程序可以作为一个参考,帮助你更好地理解和解决类似的问题。