题解 | 输出单向链表中倒数第k个结点
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
using System; using System.Collections.Generic; public class Node<T> { public T Data { get; set; } public Node<T> Next { get; set; } public Node(T t) { Data = t; Next = null; } public Node() { } } public class SingleLinkedList<T> { private Node<T> head; public SingleLinkedList() { head = new Node<T> (default(T)); } public void AddFirst(T Data) { //头插法 var a = head.Next;//1首先把头结点后的保存 var newNode = new Node<T>(Data); //2新建一个节点 存入新数据 newNode.Next = a;//3将头节点之后的在插入到新节点 保证不断 head.Next = newNode; //4插入头结点后 /*不带头结点 需要检查边界条件 比如插入第一个 * public void AddFirst(T data) { Node<T> toAdd = new Node<T>(data); toAdd.Next = head; head = toAdd; }*/ } //头插法逆序,下面写尾插法 public void AddLast(T Data) { } public Node<T> GetIndex(int index) { if (head.Next == null) return null; Node < T > temp = temp = head.Next; for (int i = 2; i <= index; i++) { if (temp.Next != null) temp = temp.Next; } return temp; } } public class Program { public static void Main() { string count; LinkedList<int> aa = new LinkedList<int>(); //定义一个链表 SingleLinkedList<int> linkedList = new SingleLinkedList<int>(); while ( !string.IsNullOrEmpty((count = Console.ReadLine()))) { int len = int.Parse(count); var a = Console.ReadLine().Split(); int[] array = Array.ConvertAll(a, int.Parse); for (int i = 0; i < len; i++) { linkedList.AddFirst(array[i]); } int k = int.Parse(Console.ReadLine()); Console.WriteLine(linkedList.GetIndex(k).Data); // Console.WriteLine(count); } /*这是讨巧 直接用数组 string count; while ( (count = Console.ReadLine()) != null) { var a = Console.ReadLine().Split(); int[] array = Array.ConvertAll(a, int.Parse); int k = int.Parse(Console.ReadLine()); Console.WriteLine(array[array.Length - k]); }*/ } }
注释是一个道友用数组完成的。本着学习的态度,从c语言之后就没有手写过链表的数据结构,想着用C#写一下 。
具体是 手写node节点的类,在写了一个单链表类 包含头插和范围指定索引出的节点。用时一小时 还没吃早饭现在去吃2025年5月18日11:12:05