C# List与单链表转换

定义简单单链表结构

    public class ListNode
    {
        public int val;
        public ListNode next;
        public ListNode(int val = 0, ListNode next = null)
        {
            this.val = val;
            this.next = next;
        }
    }

List转换为单链表,单链表转换为List的转换类

    public class ListListNodeConversion
    {
        #region List集合转换为ListNode
        public static ListNode ListToListNode(List<int> 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 List<int> ListNodeToList(ListNode listNode)
        {
            if(listNode == null)
            {
                return null;
            }

            var list = new List<int>();

            ListNode tail = listNode;
            while(tail != null)
            {
                list.Add(tail.val);
                tail = tail.next;
            }

            return list;
        }
        #endregion
    }

测试方法

            var list = new List<int> { 1, 2, 3, 4, 5, 6 };
            var nodeList = ListListNodeConversion.ListToListNode(list);
            var list1 = ListListNodeConversion.ListNodeToList(nodeList);

 

posted @ 2021-01-19 13:28  温故纳新  阅读(364)  评论(0编辑  收藏  举报