当前位置:编程学习 > C#/ASP.NET >>

删除链表中重复项

[csharp] 
<SPAN style="FONT-FAMILY: Arial, Helvetica, sans-serif">Problem</SPAN> 

Problem
Remove duplicates in a list


Solution


Sort the list.
Loop through the list. If the elements is not equal to last elements, that means a new element
[csharp] 
using System; 
using System.Collections.Generic; 
 
namespace RemoveDuplicateInList 

    class Program 
    { 
        static void RemoveDuplicates(List<int> list) 
        { 
            if(list.Count <= 1){ 
                return ; 
            } 
 
            list.Sort(); 
 
            int tail = 0; 
 
            for (int i = 1; i < list.Count; ++i) 
            { 
                if (list[i] != list[tail]) 
                { 
                    list[++tail] = list[i];            
                } 
             } 
 
            tail++; 
            list.RemoveRange(tail, list.Count - tail); 
        } 
 
        static void Main(string[] args) 
        { 
             
            List<int> list = new List<int>(); 
 
            Random random = new Random(100); 
 
            for (int i = 0; i < 41; i++) 
            { 
                list.Add(random.Next(0, 50)); 
            } 
 
            Console.WriteLine("Before removing duplicate "); 
            foreach (int k in list) 
            { 
                Console.Write(" {0} ", k); 
            } 
 
            Program.RemoveDuplicates(list); 
 
            Console.WriteLine("\nAfter removing duplicates"); 
            foreach (int k in list) 
            { 
                Console.Write(" {0} ", k); 
            } 
            Console.WriteLine(); 
        } 
    } 

using System;
using System.Collections.Generic;

namespace RemoveDuplicateInList
{
    class Program
    {
        static void RemoveDuplicates(List<int> list)
        {
            if(list.Count <= 1){
                return ;
            }

            list.Sort();

            int tail = 0;

            for (int i = 1; i < list.Count; ++i)
            {
                if (list[i] != list[tail])
                {
                    list[++tail] = list[i];          
                }
             }

            tail++;
            list.RemoveRange(tail, list.Count - tail);
        }

        static void Main(string[] args)
        {
           
            List<int> list = new List<int>();

            Random random = new Random(100);

            for (int i = 0; i < 41; i++)
            {
                list.Add(random.Next(0, 50));
            }

            Console.WriteLine("Before removing duplicate ");
            foreach (int k in list)
            {
                Console.Write(" {0} ", k);
            }

            Program.RemoveDuplicates(list);

 

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,