3 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個贊
我根據(jù)您提供的代碼嘗試了鏈表中的鏈表。在那里我添加了添加新節(jié)點(diǎn)和獲取兩個級別(外部和內(nèi)部鏈表)的所有節(jié)點(diǎn)的方法。請?jiān)谙旅嬲业芥湵斫Y(jié)構(gòu)的代碼以及客戶端代碼:
鏈表結(jié)構(gòu)
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貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個贊
您需要實(shí)現(xiàn)一個添加新元素的方法。
您可以通過遍歷元素直到到達(dá)第一個 next 為 null 的元素,然后將新元素分配給 next 來完成此操作?;蛘吣部梢跃S護(hù)指向最后一個元素的指針并直接訪問它。

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超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 關(guān)注
- 141 瀏覽
添加回答
舉報