例子:
输入: 1 -> 2 -> 3 -> 4, N = 3
输出: 2输入: 35 -> 15 -> 4 -> 20, N = 4
输出: 35
思路1:
- 计算链表的长度。让长度是len。
- 打印链表开头的第 (len – n + 1) 个节点。
- 时间复杂度:O(M) 其中 M 是链表
的大小 辅助空间: O(1)
// Java program to find N'th node from
// end of linked list
import java.io.*;
class LinkedList {
Node head; // head of the list
/* Linked List node */
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Function to get the Nth node from the last of a
linked list */
void printNthFromLast(int N)
{
int len = 0;
Node temp = head;
// 1) count the number of nodes in Linked List
while (temp != null) {
temp = temp.next;
len++;
}
// check if value of N is not more than length of
// the linked list
if (len < N)
return;
temp = head;
// 2) get the (len-N+1)th node from the beginning
for (int i = 1; i < len - N + 1; i++)
temp = temp.next;
System.out.println(temp.data);
}
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
// Driver's code
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.push(20);
llist.push(4);
llist.push(15);
llist.push(35);
// Function call
llist.printNthFromLast(4);
}
} // This code is contributed by Rajat Mishra
思路2:
从链表末尾开始的第 N 个节点,使用两个指针:
由于从末尾的第 N 个节点等于从开始的第 (Length – N + 1)个节点,因此想法是从链接列表的头部开始维护两个指针,并将一个指针移动到起点的第 N 个节点,然后将两个指针一起移动,直到第 N 个位置的指针到达最后一个节点。现在,稍后移动的指针指向链接列表末尾的第 N 个节点
时间复杂度:O(M) 其中 M 是链表的长度。
辅助空间: O(1)
// Java program to find N'th
// node from end
import java.io.*;
class LinkedList {
Node head; // head of the list
/* Linked List node */
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Function to get the
Nth node from end of list */
void printNthFromLast(int N)
{
Node main_ptr = head;
Node ref_ptr = head;
int count = 0;
if (head != null) {
while (count < N) {
if (ref_ptr == null) {
System.out.println(
N + " is greater than the no "
+ " of nodes in the list");
return;
}
ref_ptr = ref_ptr.next;
count++;
}
if (ref_ptr == null) {
if (head != null)
System.out.println("Node no. " + N
+ " from last is "
+ head.data);
}
else {
while (ref_ptr != null) {
main_ptr = main_ptr.next;
ref_ptr = ref_ptr.next;
}
System.out.println("Node no. " + N
+ " from last is "
+ main_ptr.data);
}
}
}
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
// Driver's code
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.push(20);
llist.push(4);
llist.push(15);
llist.push(35);
// Function call
llist.printNthFromLast(4);
}
}
// This code is contributed by Rajat Mishra