码迷,mamicode.com
首页 > 其他好文 > 详细

构建单链表

时间:2014-11-26 16:12:13      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   sp   div   log   bs   ad   as   

一:递归版本

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;
            }
        }
    }

 

构建单链表

标签:style   blog   color   sp   div   log   bs   ad   as   

原文地址:http://www.cnblogs.com/nixuebing/p/4123223.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!