构建单链表

一:递归版本

class LinkList

    {

        public class LinkNode

        {

            public int data;



            public LinkNode next;

        }



        private LinkNode head;



        public void Add(int data)

        {

            if (head == null)

            {

                head = new LinkNode() { data = data };

            }

            else

            {

                Add(head, data);

            }

        }



        public void Add(LinkNode node, int data)

        {

            if (node.next == null)

            {

                node.next = new LinkNode() { data = data };

                return;

            }



            Add(node.next, data);

        }

    }

二:非递归版本

class LinkList

    {

        public class LinkNode

        {

            public int data;



            public LinkNode next;

        }



        private LinkNode head;



        public void Add(int data)

        {

            LinkNode node = new LinkNode() { data = data };



            if (head == null)

            {

                head = node;

            }

            else

            {

                LinkNode temp = head;



                while (temp.next != null)

                {

                    temp = temp.next;

                }



                temp.next = node;

            }

        }

    }

 

你可能感兴趣的:(单链表)