数据结构之单链表系列一

题目

从链表末尾开始的第 N 个节点的程序

Input: 1 -> 2 -> 3 -> 4, N = 3
Output: 2

Input: 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值