Beispiel #1
0
        /*
         * 【例2-5】有数据类型为整型的单链表Ha和Hb,
         * 其数据元素均按从小到大的升序排列,
         * 编写一个算法将它们合并成一个表Hc,要求Hc中结点的值也是升序排列。
         *
         * 算法思路:把Ha的头结点作为Hc的头结点,
         * 依次扫描Ha和Hb的结点,
         * 比较Ha和Hb当前结点数据域的值,将较小值的结点附加到Hc的末尾,
         * 如此直到一个单链表被扫描完,
         * 然后将未完的那个单链表中余下的结点附加到Hc的末尾即可。
         */
        public LinkList <int> Merge(LinkList <int> Ha, LinkList <int> Hb)
        {
            //将两表合并成一表的算法实现如下:
            LinkList <int> Hc = new LinkList <int>();
            Node <int>     Pa = Ha.Head.Next;
            Node <int>     Pb = Hb.Head.Next;
            Node <int>     Pc = new Node <int>(); //已修正

            Hc      = Ha;                         //init Hc
            Hc.Next = null;
            #region case : while (Pa != null && Pb != null)
            while (Pa != null && Pb != null)
            {
                if (Pa.Data <= Pb.Data)
                {
                    Pc = Pa;
                    Pa = Pa.Next;
                }
                else //(Pb.Data < Pa.Data)
                {
                    Pc = Pb;
                    Pb = Pb.Next;
                }
                Hc.Append(Pc);
            }
            #endregion
            #region case : if (Pa == null)
            if (Pa == null)
            {
                Pa = Pb;
            }
            #endregion
            #region case : while (Pa != null)
            while (Pa != null)
            {
                Pc = Pa;
                Pa = Pa.Next;
                Hc.Append(Pc);
            }
            #endregion
            return(Hc);
        }
Beispiel #2
0
        public LinkList <int> Merge(LinkList <int> Ha, LinkList <int> Hb)
        {
            //将两表合并成一表的算法实现如下:
            LinkList <int> Hc = new LinkList <int>();
            Node <int>     p  = Ha.Next;
            Node <int>     q  = Hb.Next;
            Node <int>     s  = new Node <int>();

            Hc      = Ha;
            Hc.Next = null;
            while (p != null && q != null)
            {
                if (p.Data < q.Data)
                {
                    s = p;
                    p = p.Next;
                }
                else
                {
                    s = q;
                    q = q.Next;
                }
                Hc.Append(s);
            }
            if (p == null)
            {
                p = q;
            }
            while (p != null)
            {
                s = p;
                p = p.Next;
                Hc.Append(s);
            }
            return(Hc);
        }