程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#實現將兩個有序鏈表並為一個有序鏈表

C#實現將兩個有序鏈表並為一個有序鏈表

編輯:C#入門知識

 [csharp]
using System; 
using System.Collections.Generic; 
using System.Text; 
 
namespace ConsoleApplication4 

    class Program 
    { 
        static void Display(LinkedList<string> ls) 
        { 
            foreach (string s in ls) 
            { 
                Console.WriteLine(s); 
            } 
        } 
        static void MergeList(LinkedList<string> ls1, LinkedList<string> ls2, ref LinkedList<string> ls3) 
        { 
            LinkedListNode<string> p1 = ls1.First; 
            LinkedListNode<string> p2 = ls2.First; 
             
            LinkedListNode<string> p3 = new LinkedListNode<string>(""); 
            if (p1.Value.CompareTo(p2.Value) < 0) 
            { 
                p3.Value = p1.Value; 
                p1 = p1.Next; 
            } 
            else 
            { 
                p3.Value = p2.Value; 
                p2 = p2.Next; 
            } 
 
            ls3.AddFirst(p3); 
            while((p1!=null) && (p2!=null)) 
            { 
                LinkedListNode<string> p4 = new LinkedListNode<string>(""); 
 
                if (p1.Value.CompareTo(p2.Value) < 0 ) 
                { 
                    p4.Value = p1.Value; 
                    ls3.AddLast(p4); 
                    p1 = p1.Next; 
                     
                } 
                else 
                { 
                    p4.Value = p2.Value; 
                    ls3.AddLast(p4); 
                    p2 = p2.Next; 
                     
                     
                } 
                 
            } 
            
            while (p1 != null) 
            { 
                LinkedListNode<string> p5 = new LinkedListNode<string>(""); 
                p5.Value = p1.Value; 
                ls3.AddLast(p5); 
                p1 = p1.Next; 
            } 
            while (p2 != null) 
            { 
                LinkedListNode<string> p6 = new LinkedListNode<string>(""); 
                p6.Value = p2.Value; 
                ls3.AddLast(p6); 
                p2 = p2.Next; 
            } 
        } 
        static void Main(string[] args) 
        { 
            string[] words1 = { "aa", "bb", "cc" ,"cd1"}; 
            LinkedList<string> ls1 = new LinkedList<string>(words1); 
 
            string[] words2 = { "aa1","bb3","ee","xx"}; 
            LinkedList<string> ls2 = new LinkedList<string>(words2); 
 
            LinkedList<string> ls3 = new LinkedList<string>(); 
            MergeList(ls1,ls2, ref ls3); 
 
            Display(ls3); 
            Console.ReadKey(); 
        } 
    } 

作者:weishanshan00

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved