C# List与单链表转换
2021-01-22 12:18
标签:rgba turn list集合 测试 head return color next region 定义简单单链表结构 List转换为单链表,单链表转换为List的转换类 测试方法 C# List与单链表转换 标签:rgba turn list集合 测试 head return color next region 原文地址:https://www.cnblogs.com/tomorrow0/p/14297441.html public class ListNode
{
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null)
{
this.val = val;
this.next = next;
}
}
public class ListListNodeConversion
{
#region List集合转换为ListNode
public static ListNode ListToListNode(Listint> list)
{
if(list == null)
{
return null;
}
ListNode head = null, tail = null;
foreach(var t in list)
{
if(head == null)
{
head = tail = new ListNode(t);
}
else
{
tail.next = new ListNode(t);
tail = tail.next;
}
}
return head;
}
#endregion
#region ListNode转换为List
public static Listint> ListNodeToList(ListNode listNode)
{
if(listNode == null)
{
return null;
}
var list = new Listint>();
ListNode tail = listNode;
while(tail != null)
{
list.Add(tail.val);
tail = tail.next;
}
return list;
}
#endregion
}
var list = new Listint> { 1, 2, 3, 4, 5, 6 };
var nodeList = ListListNodeConversion.ListToListNode(list);
var list1 = ListListNodeConversion.ListNodeToList(nodeList);