3 回答
TA贡献1810条经验 获得超4个赞
我根据您提供的代码尝试了链表中的链表。在那里我添加了添加新节点和获取两个级别(外部和内部链表)的所有节点的方法。请在下面找到链表结构的代码以及客户端代码:
链表结构
public class RoomList<T> where T : class
{
private DailyList current;
private DailyList head;
public void Add(DailyList newItem)
{
if(current != null)
current.next = newItem;
current = newItem;
if(head == null)
head = current;
}
public IEnumerable<DailyList> GetAllNodes()
{
DailyList current = head;
List<DailyList> lst = new List<DailyList>();
while (current != null)
{
lst.Add(current);
current = current.next;
}
return lst;
}
public class DailyList
{
public DailyList next;
private DailyListElement head;
private DailyListElement current;
public void Add(DailyListElement newItem)
{
if(current != null)
current.next = newItem;
current = newItem;
if(head == null)
head = current;
}
public IEnumerable<DailyListElement> GetAllNodes()
{
DailyListElement current = head;
List<DailyListElement> lst = new List<DailyListElement>();
while (current != null)
{
lst.Add(current);
current = current.next;
}
return lst;
}
public class DailyListElement
{
public T data;
public DailyListElement next;
}
}
}
客户端代码:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var lst =new RoomList<string>();
var upperNode = new RoomList<string>.DailyList();
var element = new RoomList<string>.DailyList.DailyListElement();
element.data = "first";
upperNode.Add(element);
element = new RoomList<string>.DailyList.DailyListElement();
element.data = "second";
upperNode.Add(element);
lst.Add(upperNode);
upperNode = new RoomList<string>.DailyList();
element = new RoomList<string>.DailyList.DailyListElement();
element.data = "third";
upperNode.Add(element);
element = new RoomList<string>.DailyList.DailyListElement();
element.data = "fourth";
upperNode.Add(element);
lst.Add(upperNode);
foreach(var item in lst.GetAllNodes())
{
foreach(var child in item.GetAllNodes())
{
Console.WriteLine(child.data);
}
}
}
}
TA贡献1828条经验 获得超6个赞
您需要实现一个添加新元素的方法。
您可以通过遍历元素直到到达第一个 next 为 null 的元素,然后将新元素分配给 next 来完成此操作。或者您也可以维护指向最后一个元素的指针并直接访问它。
TA贡献1829条经验 获得超13个赞
您需要将方法添加Add到您的RoomList类DailyList中。
public class RoomList<T>
{
public DailyList head;
public DailyList Add()
{
var newItem = new DailyList();
if (head != null) head.next = newItem;
head = newItem;
return newItem;
}
public class DailyList
{
public DailyList next;
public DailyListElement head;
public DailyListElement Add()
{
var newItem = new DailyListElement();
if (head != null) head.next = newItem;
head = newItem;
return newItem;
}
public class DailyListElement
{
public T data;
public DailyListElement next;
}
}
}
使用示例:
var roomList = new RoomList<string>();
var dailyList = roomList.Add();
var dailyListElement = dailyList.Add();
dailyListElement.data = "StackOverflow rocks!";
Console.WriteLine(roomList.head.head.data);
输出:
StackOverflow 摇滚!
- 3 回答
- 0 关注
- 100 浏览
添加回答
举报