题目
从链表末尾开始的第 N 个节点的程序
Input: 1 -> 2 -> 3 -> 4, N = 3
Output: 2Input: 35 -> 15 -> 4 -> 20, N = 4
Output: 35
思路
使用双指针
- 维护两个指针 main_ptr 和 ref_ptr
- 将 ref_ptr 从开始移动到第 N 个节点
- 现在移动 main_ptr 和 ref_ptr,直到 ref_ptr 到达最后一个节点
- 现在打印 main_ptr 的数据,因为它位于末尾的第 N 个节点处
using System;
public class LinkedList {
Node head;
public class Node {
public int data;
public Node next;
public Node(int d)
{
data = d;
next = null;
}
}
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) {
Console.WriteLine(
N + " is greater than the no "
+ " of nodes in the list");
return;
}
ref_ptr = ref_ptr.next;
count++;
}
if (ref_ptr == null) {
head = head.next;
if (head != null)
Console.WriteLine("Node no. " + N
+ " from last is "
+ main_ptr.data);
}
else {
while (ref_ptr != null) {
main_ptr = main_ptr.next;
ref_ptr = ref_ptr.next;
}
Console.WriteLine("Node no. " + N
+ " from last is "
+ main_ptr.data);
}
}
}
public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
public static void Main(String[] args)
{
LinkedList llist = new LinkedList();
llist.push(20);
llist.push(4);
llist.push(15);
llist.push(35);
llist.printNthFromLast(4);
}
}
35->15->4->20->NULL
Node no. 4 from end is: 35