예제 #1
0
 static void Main(string[] args)
 {
     LinkedListNode<string> node = new
     LinkedListNode<string>("KARTHIK");
     LinkedList<string> names = new LinkedList<string>();
     names.AddFirst(node);
     LinkedListNode<string> node1 = new
     LinkedListNode<string>
     ("ANIL");
     names.AddAfter(node, node1);
     LinkedListNode<string> node2 = new
     LinkedListNode<string>
     ("SUMAN");
     names.AddAfter(node1, node2);
     LinkedListNode<string> node3 = new LinkedListNode
     <string>(null);
     LinkedListNode<string> aNode = names.First;
     while (aNode != null)
     {
         Console.WriteLine(aNode.Value);
         aNode = aNode.Next;
     }
     aNode = names.Find("David");
     if (aNode != null) aNode = names.First;
     while (aNode != null)
     {
         Console.WriteLine(aNode.Value);
         aNode = aNode.Next;
     }
     Console.Read();
 }
예제 #2
0
        public void MethodUnderTest_TestedBehavior_ExpectedResult()
        {
            var nodeList = new LinkedList<object>();
            nodeList.Add(new ListNode<object>(1));
            nodeList.Add(new ListNode<object>(2));
            nodeList.Add(new ListNode<object>(3));
            nodeList.Add(new ListNode<object>(4));
            nodeList.Add(new ListNode<object>(5));
            nodeList.Add(new ListNode<object>(6));
            nodeList.Add(new ListNode<object>("d"));
            nodeList.Add(new ListNode<object>("g"));
            nodeList.AddAfter(3, new ListNode<object>("B"));
            nodeList.AddAfter("g", new ListNode<object>("uber"));

            Console.WriteLine(nodeList.Tail);


            Console.WriteLine("The list has {0} elements!", nodeList.ListSize);
            nodeList.Traverse();
            nodeList.Reverse();
            nodeList.Traverse();

            Assert.That(nodeList.ListSize, Is.EqualTo(10));
            Assert.That(nodeList.Contains("g"), Is.True);

            nodeList.Remove("d");
            nodeList.Remove("g");

            Assert.That(nodeList.ListSize, Is.EqualTo(8));
            Assert.That(nodeList.Contains("g"), Is.False);

            nodeList.Reverse();
            nodeList.Traverse();
        }
        public void ExploreLinkedLists()
        {
            // a LinkedList is a doubly linked list
            var linkedList = new LinkedList<string>();
            linkedList.AddFirst("1");
            // first argument accepts a "LinkedListNode"
            linkedList.AddAfter(linkedList.First, "2");
            linkedList.AddLast("3");
            linkedList.AddAfter(linkedList.Find("2"), "4");

            var orderedArray = linkedList.ToArray();
            // order should be 1,2,4,3
            Assert.That(orderedArray[0], Is.EqualTo("1"));
            Assert.That(orderedArray[1], Is.EqualTo("2"));
            Assert.That(orderedArray[2], Is.EqualTo("4"));
            Assert.That(orderedArray[3], Is.EqualTo("3"));

            // advantages:
            //  insertion is really easy

            // disadvantages:
            // looping through the objects is harder because they arent saved on contigous memory blocks

            // most of the time it is best NOT to use linked lists
            // essentially they are only good for insert/remove in the middle of lists
            // LinkedList<T> does NOT implement IList<T> - so does not have alot of useful methods
            // List<T> is much faster for random access (because backed by Array)
            // SEE: https://stackoverflow.com/questions/169973/when-should-i-use-a-list-vs-a-linkedlist
        }
예제 #4
0
 public void NoCycle()
 {
     var list = new LinkedList<string>();
     var first = list.AddFirst(new LinkedListNode<string>("first"));
     list.AddAfter(first, new LinkedListNode<string>("second"));
     var second = first.Next;
     list.AddAfter(second, new LinkedListNode<string>("third"));
     var detection = new CycleDetection<string>(list);
     Assert.That(detection.HasCycle, Is.False);
 }
        public void LinkedList()
        {
            var list = new LinkedList<string>();
            var first = list.AddFirst("Matteo");
            var second = list.AddAfter(first, "Pierangeli");
            var third = list.AddAfter(second, "ha");
            var fourth = list.AddAfter(third, "32");
            var fifth = list.AddAfter(fourth, "anni");

            Assert.That(third.Previous.Value, Is.EqualTo("Pierangeli"));
            Assert.That(third.Next.Value, Is.EqualTo("32"));
        }
예제 #6
0
        public static void Main(string[] args)
        {
            /* Creating a Simple Linked List */

            LinkedList<Object> MyLinkedList = new LinkedList<Object>();

            /* Inserting Elements */

            MyLinkedList.AddLast ("Add");
            MyLinkedList.AddLast(4);

            /* Implementing Find */

            MyLinkedList.AddAfter(MyLinkedList.Find("Add"), 'a');

            /* Printing Elements of the List */

            PrintList (MyLinkedList);

            /* Remove a particular element from the List */

            MyLinkedList.Remove (4);

            PrintList (MyLinkedList);

            /* Printing the Count of the List */

            int linkedListCount = MyLinkedList.Count;

            Console.WriteLine (linkedListCount);
        }
예제 #7
0
        static void Main(string[] args)
        {
            LinkedList<string> sporcular = new LinkedList<string>();
            sporcular.AddLast("A");
            sporcular.AddLast("B");
            sporcular.AddLast("C");
            sporcular.AddLast("D");
            sporcular.AddLast("E");
            sporcular.AddLast("F");
            sporcular.AddLast("G");
            sporcular.AddLast("H");

            sporcular.Remove("H");
            sporcular.AddFirst("H");

            sporcular.Remove("E");
            sporcular.AddFirst("E");

            sporcular.AddAfter(sporcular.First, "X");

            LinkedListNode<string> c =
                sporcular.Find("C");

            sporcular.AddBefore(c, "Y");

            foreach (string item in sporcular)
            {
                Console.WriteLine(item);
            }
        }
예제 #8
0
 public void CycleDetectStartElement()
 {
     var list = new LinkedList<string>();
     var first = list.AddFirst(new LinkedListNode<string>("first"));
     var second = list.AddAfter(
         first,
         new LinkedListNode<string>("second")
     );
     list.AddAfter(
         second,
         new LinkedListNode<string>("third")
     );
     list.AddLast(second);
     var detection = new CycleDetection<string>(list);
     Assert.That(detection.CycleBeginning, Is.EqualTo(second));
 }
예제 #9
0
        static void Main(string[] args)
        {
            List<int> list = new List<int>
            {
                3,2,
            }; // 3, 2

            list.Add(5); // 3, 2, 5
            list.Add(6); // 3, 2, 5, 6
            list.Remove(5); // 3, 2, 6

            Queue<int> queue = new Queue<int>();
            queue.Enqueue(3);// 3
            queue.Enqueue(8);// 3, 8
            queue.Dequeue(); // 8

            Stack<int> stack = new Stack<int>();
            stack.Push(2); // 2
            stack.Push(7); // 7, 2
            stack.Push(8); // 8, 7, 2
            stack.Pop();   // 7, 2

            foreach (var i in stack)
            {
                Console.WriteLine(i);
            }

            LinkedList<int> linkedList = new LinkedList<int>();
            linkedList.AddFirst(9); // 9
            linkedList.AddAfter(linkedList.Find(9), 5); // 9, 5
            linkedList.Remove(9); // 5

            Console.Read();
        }
예제 #10
0
 public void Cycle()
 {
     var list = new LinkedList<string>();
     var first = list.AddFirst(new LinkedListNode<string>("first"));
     list.AddAfter(first, new LinkedListNode<string>("second"));
     list.AddLast(first);
     var detection = new CycleDetection<string>(list);
     Assert.That(detection.HasCycle, Is.True);
 }
예제 #11
0
        public MyClass()
        {
            LinkedList<int> test = new LinkedList<int>();
            LinkedListNode<int> node = test.AddFirst(1);
            node = test.AddAfter(node,5);
            node = test.AddAfter(node,3);
            node = test.AddBefore(node,2);
            LinkedListNode<int> third = node = test.AddAfter(node,6);
            node = test.AddAfter(node,2);

            test.AddAfter(third,4);
            node = test.First;
            while(node != null)
            {
                Console.WriteLine(node.Value);
                node = node.Next;
            }
        }
    static void Main()
    {
        LinkedList<string> list = new LinkedList<string>();
        list.AddFirst("First");
        list.AddLast("Last");
        list.AddAfter(list.First, "After First");
        list.AddBefore(list.Last, "Before Last");

        Console.WriteLine(String.Join(", ", list));
        // Result: First, After First, Before Last, Last
    }
예제 #13
0
    static void Main()
    {
        Console.WriteLine("Dot Net LinkedList");
        LinkedList<int> dotNetList = new LinkedList<int>();
        dotNetList.AddFirst(3);
        dotNetList.AddFirst(1);
        dotNetList.AddBefore(dotNetList.Last, 2);
        dotNetList.AddBefore(dotNetList.First, 4);
        dotNetList.AddAfter(dotNetList.Last, 5);
        dotNetList.AddAfter(dotNetList.First, 6);
        dotNetList.AddLast(7);
        dotNetList.AddLast(8);
        dotNetList.RemoveFirst();
        dotNetList.RemoveLast();

        foreach (var item in dotNetList)
        {
            Console.WriteLine(item);
        }
        Console.WriteLine("Dot Net LinkedList.Count = {0}", dotNetList.Count);

        Console.WriteLine();
        Console.WriteLine("My LinkedList<T>");
        MyLinkedList<int> myList = new MyLinkedList<int>();
        myList.AddFirst(3);
        myList.AddFirst(1);
        myList.AddBefore(myList.Last, 2);
        myList.AddBefore(myList.First, 4);
        myList.AddAfter(myList.Last, 5);
        myList.AddAfter(myList.First, 6);
        myList.AddLast(7);
        myList.AddLast(8);
        myList.RemoveFirst();
        myList.RemoveLast();

        foreach (var number in myList)
        {
            Console.WriteLine(number);
        }
        Console.WriteLine("MyList.Count = {0}", myList.Count);
    }
예제 #14
0
    static void Main()
    {
        LinkedList<int> ints = new LinkedList<int>(4);
        ints.AddFirst(3);
        ints.AddLast(5);
        ints.AddBefore(1, 1);
        ints.AddAfter(2, 0);
        ints.RemoveFirst();
        ints.RemoveLast();

        Console.WriteLine(ints.GetItemAt(0).Value);
    }
예제 #15
0
 static void Main(string[] args)
 {
     LinkedList<string> linked = new LinkedList<string>();
     //ape->cat->dog->man
     linked.AddLast("cats");
     linked.AddLast("dog");
     linked.AddLast("man");
     linked.AddFirst("ape");
     //ape->cat->monkey->dog->man
     LinkedListNode<string> node = linked.Find("cat");
     linked.AddAfter(node, "monkey");
 }
        public void TestAddAfterNoPrevious()
        {
            var expected = new int[3] { 0, 1, 2 };

            var list = new LinkedList<int>();
            var node = list.AddLast(0);
            list.AddLast(2);

            list.AddAfter(node, 1);

            Verify(expected, list);
        }
예제 #17
0
        public static void Main(string[] args)
        {
            LinkedList<string> list =
            new LinkedList<string>();
            list.AddFirst("1");
            list.AddLast("5");
            list.AddAfter(list.First, "2");
            list.AddBefore(list.Last, "3");
            list.AddBefore(list.Last, "4");
            list.Remove(list.First.NextItem);

            PrintList(list);
        }
        public void TestAddAfterLast()
        {
            var expected = new int[3] { 0, 1, 2 };

            var list = new LinkedList<int>();
            list.AddLast(0);
            list.AddLast(1);

            var node = list.AddAfter(list.Last, 2);

            Verify(expected, list);
            Assert.AreSame(list.Last, node);
        }
예제 #19
0
        static void Main()
        {
            LinkedList<int> numbers = new LinkedList<int>();
            for (int i = 0; i < 20; i++)
            {
                numbers.AddLast(i);
            }

            numbers.AddFirst(100);
            numbers.AddFirst(50);
            numbers.AddAfter(numbers.FirstElement, -50);

            foreach (var number in numbers)
            {
                System.Console.WriteLine(number);
            }
        }
        public override LinkedList<int> ordenar(List<int> lista)
        {
            LinkedList<int> ordenada = new LinkedList<int>();
            if (null == lista || lista.Count == 0)
                return null;
            if (ordenada.Count == 0)
                ordenada.AddFirst(lista[0]);
            for (int i = 1; i < lista.Count; i++)
            {
                if (lista[i] < ordenada.First.Value)
                {
                    ordenada.AddFirst(lista[i]);
                }
                else
                {
                    LinkedListNode<int> node = ordenada.First;
                    while (null != node)
                    {
                        if (null != node.Next)
                        {
                            if (lista[i] > node.Value)
                            {
                                node = node.Next;
                            }
                            else
                            {
                                ordenada.AddBefore(node, lista[i]);
                                break;
                            }
                        }
                        else
                        {
                            if (lista[i] > node.Value)
                                ordenada.AddAfter(node, lista[i]);
                            else
                                ordenada.AddBefore(node, lista[i]);
                            break;
                        }

                    }
                }

            }

            return ordenada;
        }
예제 #21
0
        public static void Main(string[] args)
        {
            LinkedList<object> linkedList = new LinkedList<object> ();
            linkedList.AddFirst (1);
            linkedList.AddAfter (linkedList.Find(1),2);
            linkedList.AddLast ("Bye");
            linkedList.AddBefore (linkedList.Find(1),3.55);

            Console.WriteLine ("The Elements are: ");

            PrintElements (linkedList);
            Console.WriteLine ("No. of items in list: {0}",linkedList.Count);

            linkedList.Remove (1);
            Console.WriteLine ("The Elements after removing are: ");
            PrintElements (linkedList);
            Console.WriteLine ("No. of items in list after removing: {0}",linkedList.Count);
        }
예제 #22
0
 private void AddToList(LinkedList<Pair> list, Pair pair)
 {
     if(list.Count == 0)
     {
         list.AddFirst(pair);
         return;
     }
     LinkedListNode<Pair> node = list.Last;
     while(node != null)
     {
         if(String.CompareOrdinal(pair.Key, node.Value.Key) >= 0)
         {
             list.AddAfter(node, pair);
             return;
         }
         node = node.Previous;
     }
     list.AddFirst(pair);
 }
    static void Main()
    {
        LinkedList<int> myLinkedList = new LinkedList<int>();
            myLinkedList.AddFirst(1);
            myLinkedList.AddLast(5000);
            myLinkedList.AddFirst(10);
            myLinkedList.AddLast(500);
            myLinkedList.AddAfter(myLinkedList.FirstElement.NextItem, 100000000);
            myLinkedList.AddBefore(myLinkedList.FirstElement.NextItem, 500000000);
            myLinkedList.PrintList();
            Console.WriteLine("the count={0}",myLinkedList.Count);

            Console.WriteLine();
            Console.WriteLine("after removing of some elements");
            myLinkedList.RemoveFirst();
            myLinkedList.RemoveLast();
            myLinkedList.PrintList();
            Console.WriteLine("the count={0}",myLinkedList.Count);
    }
예제 #24
0
 private void Frm_Main_Load(object sender, EventArgs e)
 {
     //构建泛型双向链表
     LinkedList<int> ints = new LinkedList<int>();
     ints.AddFirst(0);//添加第一个元素
     for (int i = 1; i < 10; i++)
     {
         ints.AddAfter(ints.Find(i - 1), i);//向泛型双向链表中添加元素
     }
     //LINQ过滤、排序泛型双向链表
     var query = from item in ints
                 where item > 0 && item < 9
                 orderby item descending
                 select item;
     //显示查询结果
     foreach (var item in query)
     {
         label1.Text += item.ToString() + "<=";
     }
 }
예제 #25
0
        static void Main(string[] args)
        {
            var presidents = new LinkedList<string>();
            presidents.AddLast("JFK");
            presidents.AddLast("Lyndon B. Johnson");
            presidents.AddLast("Richard Nixon");
            presidents.AddLast("Jimmy Carter");

            presidents.RemoveFirst();
            LinkedListNode<string> kennedy = presidents.AddFirst("John F. Kennedy");

            // works but inefficient
            LinkedListNode<string> nixon = presidents.Find("Richard Nixon");
            presidents.AddAfter(nixon, "Gerald Ford");

            foreach (string president in presidents)
            {
                Console.WriteLine(president);
            }
        }
예제 #26
0
        static void Main()
        {
            LinkedList<int> linkedList = new LinkedList<int>();
            linkedList.AddFirst(5);
            linkedList.AddLast(100);
            linkedList.AddAfter(linkedList.FirstElement.NextItem, 1000);
            linkedList.AddBefore(linkedList.FirstElement.NextItem, 999);
            linkedList.AddBefore(linkedList.FirstElement, 0);
            linkedList.RemoveFirst();
            linkedList.RemoveLast();

            ListItem<int> next = linkedList.FirstElement;
            while (next != null)
            {
                Console.WriteLine(next.Value);
                next = next.NextItem;
            }

            Console.WriteLine(linkedList.Count);
        }
        static void Main(string[] args)
        {
            LinkedList<string> list = new LinkedList<string>();
            list.AddFirst(".AddFirst() adds at the head.");
            list.AddLast(".AddLast() adds at the tail.");
            LinkedListNode<string> head = list.Find(".AddFirst() adds at the head.");
            list.AddAfter(head, ".AddAfter() adds after a specified node.");
            LinkedListNode<string> tail = list.Find(".AddLast() adds at the tail.");
            list.AddBefore(tail, "Betcha can't guess what .AddBefore() does.");

            System.Console.WriteLine("Forward:");
            foreach (string nodeValue in list) { System.Console.WriteLine(nodeValue); }

            System.Console.WriteLine("\nBackward:");
            LinkedListNode<string> current = tail;
            while (current != null)
            {
                System.Console.WriteLine(current.Value);
                current = current.Previous;
            }
        }
예제 #28
0
        public int NthSuperUglyNumber(int n, int[] primes)
        {
            LinkedList<long> list = new LinkedList<long>();
            list.AddFirst(1);
            LinkedListNode<long>[] hints = new LinkedListNode<long>[primes.Length];
            var minNode = list.First;
            long min = 0;
            int size = n;
            while (n-- > 0)
            {
                min = minNode.Value;
                for (int i = 0; i < primes.Length; i++)
                {
                    var current = hints[i];
                    if (current == null)
                        current = list.First;

                    long p = primes[i];
                    while (current.Next != null && current.Next.Value <= p * min)
                    {
                        current = current.Next;
                    }
                    hints[i] = current;
                    if (current.Value == p * min)
                        continue;

                    if (list.Count > size && list.Last.Value < p * min)
                    {
                        break;
                    }

                    list.AddAfter(current, p * min);

                }
                minNode = minNode.Next;
            }

            return (int)min;
        }
예제 #29
0
        static void Main(string[] args)
        {
            var list = new LinkedList<int>();
            list.AddFirst(2);
            list.AddFirst(1);
            var node = list.Find(2);
            list.AddAfter(node,3);

            foreach (var item in list)
            {
                Console.WriteLine(item);
            }

            list.AddBefore(node,7);

            Console.WriteLine("----------Adding Before 2-----------------");

            foreach (var i in list)
            {
                Console.WriteLine(i);
            }
        }
        static void Main(string[] args)
        {
            var presidents = new LinkedList<string>();
            // Add items to the presidenst linked list.
            presidents.AddLast("JFK");
            presidents.AddLast("Lyndon B Johnson");
            presidents.AddLast("Richard Nixon");
            presidents.AddLast("Jimmy Carter");

            presidents.RemoveFirst();
            presidents.AddFirst("John F. Kennedy");
            // For creating a linked list node directly
            LinkedListNode<string> kennedy = presidents.AddFirst("John F. Kennedy");

            // To put a value before or after a value, the value has to be a LinkedListNode.
            LinkedListNode<string> nixon = presidents.Find("Richard Nixon");
            presidents.AddAfter(nixon, "Gerald Ford");

            foreach (string president in presidents)
            {
                Console.WriteLine(president);
            }
        }
예제 #31
0
        protected async Task AllocateBlocks(IProgress <string> ProgressStatus, IProgress <int> ProgressPercentage, uint startingID = 0)
        {
            uint ID = startingID;

            ProgressStatus.Report("First pass hash caching...\r\n");

            await GenerateHashes(Files, ProgressPercentage);


            ProgressStatus.Report("Second pass writing...\r\n");

            ProgressStatus.Report("Allocating chunks...\r\n");
            ProgressPercentage.Report(0);

            //Create a LST chunk
            var lstChunk = new QueuedChunk(new List <ISubfile>(), ID++, DefaultCompression, 23);

            //bunch duplicate files together
            //going to assume OrderBy is a stable sort
            LinkedList <ISubfile> linkedSubfileList = new LinkedList <ISubfile>(
                Files
                .OrderBy(x => x.Name)                                //order by file name first
                .OrderBy(x => Path.GetExtension(x.Name) ?? x.Name)); //then we order by file type, preserving duplicate file order

            Dictionary <Md5Hash, LinkedListNode <ISubfile> > HashList = new Dictionary <Md5Hash, LinkedListNode <ISubfile> >();

            var node = linkedSubfileList.First;

            while (node?.Next != null)
            {
                ISubfile file = node.Value;
                Md5Hash  hash = file.Source.Md5;

                if (HashList.ContainsKey(hash))
                {
                    var nextNode = node.Next;

                    var originalNode = HashList[hash];

                    linkedSubfileList.Remove(node);
                    linkedSubfileList.AddAfter(originalNode, file);

                    node = nextNode;
                }
                else
                {
                    HashList.Add(hash, node);

                    node = node.Next;
                }
            }

            var fileList = new Queue <ISubfile>(linkedSubfileList);

            ulong accumulatedSize = 0;

            var     currentChunk = new QueuedChunk(new List <ISubfile>(), ID++, DefaultCompression, 23);
            Md5Hash?previousHash = null;

            while (fileList.Count > 0)
            {
                ISubfile file = fileList.Dequeue();

                if (previousHash.HasValue && previousHash.Value == file.Source.Md5)
                {
                    currentChunk.Subfiles.Add(file);
                    continue;
                }

                previousHash = file.Source.Md5;

                accumulatedSize += file.Source.Size;

                if (file.Name.EndsWith(".lst"))
                {
                    lstChunk.Subfiles.Add(file);
                    continue;
                }

                if (file.Type == ArchiveFileType.WaveAudio || file.Type == ArchiveFileType.OpusAudio)
                {
                    //non-compressable data, assign it and any duplicates to a new chunk

                    List <ISubfile> opusFiles = new List <ISubfile>();

                    opusFiles.Add(file);

                    byte[] md5Template = file.Source.Md5;

                    //keep peeking and dequeuing until we find another file
                    while (true)
                    {
                        if (fileList.Count == 0)
                        {
                            break; //no more files, need to stop
                        }
                        ISubfile next = fileList.Peek();

                        if (!Utility.CompareBytes(
                                md5Template,
                                next.Source.Md5))
                        {
                            //we've stopped finding duplicates
                            break;
                        }

                        opusFiles.Add(fileList.Dequeue());
                    }

                    var tempChunk = new QueuedChunk(opusFiles, ID++, ArchiveChunkCompression.Uncompressed, 0);
                    QueuedChunks.Add(tempChunk);

                    continue;
                }

                if (file.Size + accumulatedSize > ChunkSizeLimit)
                {
                    //cut off the chunk here
                    QueuedChunks.Add(currentChunk);

                    accumulatedSize = 0;

                    //create a new chunk
                    currentChunk = new QueuedChunk(new List <ISubfile>(), ID++, DefaultCompression, 23);
                }

                currentChunk.Subfiles.Add(file);
            }

            if (currentChunk.Subfiles.Count > 0)
            {
                QueuedChunks.Add(currentChunk);
            }

            if (lstChunk.Subfiles.Count > 0)
            {
                QueuedChunks.Add(lstChunk);
            }

            QueuedChunks.CompleteAdding();
        }
예제 #32
0
        }//________________________________________________________________________----------------------------

        public ColaElement AgregarElementoTabAreas(TableLayoutPanel t, TareaEntity tarea)
        {
            //foreach (Particion a in llPart)
            //{
            //    Console.WriteLine(a.num + "|" + a.tam + "|" + a.dir + "|" + a.proceso + "|" + a.estado);
            //}
            //Console.WriteLine("\n----------------------------------\n");
            if (filaLibreAreas.Count != 0 && encontrado == 0)
            {
                // Revisa si hay espacios disponibles si no, inserta uno nuevo
                Area prueba = new Area();
                foreach (int x in filaLibreAreas)
                {
                    prueba = null;
                    for (var node = llArea.First; node != null; node = node.Next)
                    {
                        if (node.Value.num == x)
                        {
                            prueba = node.Value;
                            break;
                        }
                    }
                    if (prueba.tam == tarea.GetTamañoTarea())
                    {
                        llArea.AddAfter(llArea.Find(prueba), new LinkedListNode <Area>(new Area(x, tarea.GetTamañoTarea(), prueba.dir, "A", tarea)));
                        llArea.Remove(prueba);
                        ActualizarTabla(t);
                        filaLibreAreas.Remove(x);
                        encontrado = 0;
                        break;
                    }
                    else if (prueba.tam > tarea.GetTamañoTarea())
                    {
                        LinkedListNode <Area> p = llArea.Find(prueba);
                        llArea.AddBefore(p, new LinkedListNode <Area>(new Area(x, tarea.GetTamañoTarea(), prueba.dir, "A", tarea)));
                        p.Value.dir = p.Previous.Value.tam + prueba.dir;
                        p.Value.tam = prueba.tam - p.Previous.Value.tam;
                        ActualizarTabla(t);
                        filaLibreAreas.Remove(x);
                        encontrado = 0;
                        filaLibreAreas.Add(x + 1);
                        numArea++;
                        break;
                    }
                    else
                    {
                        encontrado = 1;
                        AgregarElementoTabAreas(t, tarea);
                    }
                }
            }
            else if (llArea.First == null)
            {
                llArea.AddFirst(new Area(numArea, tarea.GetTamañoTarea(), 0, "A", tarea));
                numArea++;
                AñadirUltimoATabla(t);
                //DejarVacioElementoTabAreas(t, 0);  PARA PRUEBA UNITARIA
            }
            else
            {
                if (llArea.Last.Value.dir + llArea.Last.Value.tam + tarea.GetTamañoTarea() > espacioDisponible)
                {
                    tarea.SetPrioridad(tarea.GetPrioridad() + 1);
                    return(new ColaElement(tarea));
                }
                llArea.AddLast(new Area(numArea, tarea.GetTamañoTarea(), llArea.Last.Value.dir + llArea.Last.Value.tam, "A", tarea));
                numArea++;
                AñadirUltimoATabla(t);
            }
            encontrado = 0;
            tarea.SetPrioridad(0);// tarea fue añadida a Tabla de Areas Disp.
            return(new ColaElement(tarea));
        }
예제 #33
0
        public void Fitting(Func <CompressedTimeSpan, float> originalCurve, CompressedTimeSpan stepSize, float maxErrorThreshold)
        {
            // Some info: http://wscg.zcu.cz/wscg2008/Papers_2008/full/A23-full.pdf
            // Compression of Temporal Video Data by Catmull-Rom Spline and Quadratic Bézier Curve Fitting
            // And: http://bitsquid.blogspot.jp/2009/11/bitsquid-low-level-animation-system.html

            // Only one or zero keys: no need to do anything.
            if (KeyFrames.Count <= 1)
            {
                return;
            }

            var keyFrames = new LinkedList <KeyFrameData <float> >(this.KeyFrames);
            var evaluator = new Evaluator(keyFrames);

            // Compute initial errors (using Least Square Equation)
            var errors = new LinkedList <ErrorNode>();
            //var errors = new List<float>();
            var errorQueue = new PriorityQueue <LinkedListNode <ErrorNode> >(new ErrorComparer());

            foreach (var keyFrame in keyFrames.EnumerateNodes())
            {
                if (keyFrame.Next == null)
                {
                    break;
                }
                var error     = EvaluateError(originalCurve, evaluator, stepSize, keyFrame.Value, keyFrame.Next.Value);
                var errorNode = errors.AddLast(new ErrorNode(keyFrame, error.Key, error.Value));
                errorQueue.Enqueue(errorNode);
            }
            //for (int keyFrame = 0; keyFrame < KeyFrames.Count - 1; ++keyFrame)
            //{
            //    //errors.Add(EvaluateError(originalCurve, evaluator, stepSize, keyFrame));
            //    var errorNode = errors.AddLast(new ErrorNode(EvaluateError(originalCurve, evaluator, stepSize, keyFrame)));
            //    errorQueue.Enqueue(errorNode);
            //}

            while (true)
            {
                // Already reached enough subdivisions
                var highestError = errorQueue.Dequeue();
                if (highestError.Value.Error <= maxErrorThreshold)
                {
                    break;
                }

                //// Find segment to optimize
                //var biggestErrorIndex = 0;
                //for (int keyFrame = 1; keyFrame < KeyFrames.Count - 1; ++keyFrame)
                //{
                //    if (errors[keyFrame] > errors[biggestErrorIndex])
                //        biggestErrorIndex = keyFrame;
                //}

                //// Already reached enough subdivisions
                //if (errors[biggestErrorIndex] <= maxErrorThreshold)
                //    break;

                // Create new key (use middle point, but better heuristic might improve situation -- like point with biggest error)
                //var middleTime = (start.Value.Time + end.Value.Time) / 2;
                var middleTime = highestError.Value.BiggestDeltaTime;
                //KeyFrames.Insert(biggestErrorIndex + 1, new KeyFrameData<float> { Time = middleTime, Value = originalCurve(middleTime) });
                var newKeyFrame = keyFrames.AddAfter(highestError.Value.KeyFrame, new KeyFrameData <float> {
                    Time = middleTime, Value = originalCurve(middleTime)
                });
                //errors.Insert(biggestErrorIndex + 1, 0.0f);
                var newError = errors.AddAfter(highestError, new ErrorNode(newKeyFrame, CompressedTimeSpan.Zero, 0.0f));

                var highestErrorLastUpdate = newError;
                if (highestErrorLastUpdate.Next != null)
                {
                    highestErrorLastUpdate = highestErrorLastUpdate.Next;
                }

                // Invalidate evaluator (data changed)
                evaluator.InvalidateTime();

                // Update errors
                for (var error = highestError.Previous ?? highestError; error != null; error = error.Next)
                {
                    if (error != highestError && error != newError)
                    {
                        errorQueue.Remove(error);
                    }

                    var errorInfo = EvaluateError(originalCurve, evaluator, stepSize, error.Value.KeyFrame.Value, error.Value.KeyFrame.Next.Value);
                    error.Value.BiggestDeltaTime = errorInfo.Key;
                    error.Value.Error            = errorInfo.Value;

                    errorQueue.Enqueue(error);

                    if (error == highestErrorLastUpdate)
                    {
                        break;
                    }
                }
            }

            KeyFrames = new List <KeyFrameData <float> >(keyFrames);
        }
예제 #34
0
        private static ICollection BuildResult(List <Entry> map)
        {
            LinkedList <IAdaptable>     result    = new LinkedList <IAdaptable>();
            LinkedListNode <IAdaptable> firstzone = null;
            LinkedListNode <IAdaptable> lastzone  = null;

            foreach (Entry e in map)
            {
                if (e.dependency == null)
                {
                    //依存物なしのばあい、first-dontcare-lastの各ゾーン順で並ぶ。各ゾーン内は元の入力順を保持

                    //designationなしはDontCareに等しい
                    if (e.designation == null || e.designation.DesignationPosition == PositionType.DontCare)
                    {
                        if (lastzone == null)
                        {
                            result.AddLast(e.content);
                        }
                        else
                        {
                            result.AddBefore(lastzone, e.content);
                        }
                    }
                    else if (e.designation.DesignationPosition == PositionType.First)
                    {
                        if (firstzone == null)
                        {
                            firstzone = result.AddFirst(e.content);
                        }
                        else
                        {
                            firstzone = result.AddAfter(firstzone, e.content);
                        }
                    }
                    else if (e.designation.DesignationPosition == PositionType.Last)
                    {
                        if (lastzone == null)
                        {
                            lastzone = result.AddLast(e.content);
                        }
                        else
                        {
                            lastzone = result.AddBefore(lastzone, e.content);
                        }
                    }
                }
                else   //依存物あり
                {
                    LinkedListNode <IAdaptable> n = result.Find(e.dependency.content);
                    Debug.Assert(n != null);
                    Debug.Assert(e.designation.DesignationPosition != PositionType.DontCare);
                    if (e.designation.DesignationPosition == PositionType.NextTo)
                    {
                        result.AddAfter(n, e.content);
                    }
                    else
                    {
                        result.AddBefore(n, e.content);
                    }
                }
            }
            return(result);
        }
예제 #35
0
        static void Main(string[] args)
        {
            // instancier notre liste chainée avec les entiers 5, 10 et 4.
            int[]            mesEntiers     = { 5, 10, 4 };
            LinkedList <int> maListeEntiers = new LinkedList <int>(mesEntiers);

            foreach (int item in maListeEntiers)
            {
                Console.WriteLine(item);
            }

            // afficher les éléments de la liste chainée en utilisant la propriété qui accède au premier élément


            // afficher les éléments de la liste chainée en utilisant la propriété qui accède à un élément par son indice
            for (int i = 0; i < maListeEntiers.Count; i++)
            {
                Console.WriteLine(maListeEntiers.ElementAt(i));
            }

            Console.WriteLine("Insertion de deux éléments");
            // inserer 99 à la première position
            maListeEntiers.AddFirst(99);

            // inserer 33 à la seconde position
            maListeEntiers.AddAfter(maListeEntiers.Find(99), 33);

            // inserer 30 à la seconde position
            maListeEntiers.AddAfter(maListeEntiers.Find(99), 30);

            // afficher tout
            for (int i = 0; i < maListeEntiers.Count; i++)
            {
                Console.WriteLine(maListeEntiers.ElementAt(i));
            }

            Console.WriteLine("----------------------------------Utilisation de ma propre liste chainée--------------------------------------------");
            ListeChainee <int> listeChainee = new ListeChainee <int>();

            listeChainee.Ajouter(5);
            listeChainee.Ajouter(10);
            listeChainee.Ajouter(4);
            Console.WriteLine("listeChainee.Premier.Valeur : " + listeChainee.Premier.Valeur);
            Console.WriteLine("listeChainee.Premier.Suivant.Valeur : " + listeChainee.Premier.Suivant.Valeur);
            Console.WriteLine("listeChainee.Premier.Suivant.Suivant.Valeur : " + listeChainee.Premier.Suivant.Suivant.Valeur);
            Console.WriteLine("****************************************");
            Console.WriteLine(listeChainee.ObtenirElement(0).Valeur);
            Console.WriteLine(listeChainee.ObtenirElement(1).Valeur);
            Console.WriteLine(listeChainee.ObtenirElement(2).Valeur);
            Console.WriteLine("*************");
            listeChainee.Inserer(99, 0);
            listeChainee.Inserer(33, 2);
            listeChainee.Inserer(30, 2);
            Console.WriteLine(listeChainee.ObtenirElement(0).Valeur);
            Console.WriteLine(listeChainee.ObtenirElement(1).Valeur);
            Console.WriteLine(listeChainee.ObtenirElement(2).Valeur);
            Console.WriteLine(listeChainee.ObtenirElement(3).Valeur);
            Console.WriteLine(listeChainee.ObtenirElement(4).Valeur);
            Console.WriteLine(listeChainee.ObtenirElement(5).Valeur);

            /*
             * ----------------------------------Utilisation de ma propre liste chainée--------
             * ------------------------------------
             * listeChainee.Premier.Valeur : 5
             * listeChainee.Premier.Suivant.Valeur : 10
             * listeChainee.Premier.Suivant.Suivant.Valeur : 4
             ****************************************
             * 5
             * 5
             * 10
             *************
             *************99
             *************99
             *************30
             *************33
             *************5
             *************10
             * */



            Console.WriteLine("Fin du test, tapez sur une touche pour sortir");
            Console.ReadKey();
        }
예제 #36
0
        // Creates a linked list of all vertices in the polygon, with the hole vertices joined to the hull at optimal points.
        LinkedList <Vertex> GenerateVertexList(Polygon polygon)
        {
            LinkedList <Vertex>     vertexList  = new LinkedList <Vertex>();
            LinkedListNode <Vertex> currentNode = null;

            // Add all hull points to the linked list
            for (int i = 0; i < polygon.numHullPoints; i++)
            {
                int prevPointIndex = (i - 1 + polygon.numHullPoints) % polygon.numHullPoints;
                int nextPointIndex = (i + 1) % polygon.numHullPoints;

                bool   vertexIsConvex    = IsConvex(polygon.points[prevPointIndex], polygon.points[i], polygon.points[nextPointIndex]);
                Vertex currentHullVertex = new Vertex(polygon.points[i], i, vertexIsConvex);

                if (currentNode == null)
                {
                    currentNode = vertexList.AddFirst(currentHullVertex);
                }
                else
                {
                    currentNode = vertexList.AddAfter(currentNode, currentHullVertex);
                }
            }

            // Process holes:
            List <HoleData> sortedHoleData = new List <HoleData>();

            for (int holeIndex = 0; holeIndex < polygon.numHoles; holeIndex++)
            {
                // Find index of rightmost point in hole. This 'bridge' point is where the hole will be connected to the hull.
                Vector2 holeBridgePoint = new Vector2(float.MinValue, 0);
                int     holeBridgeIndex = 0;
                for (int i = 0; i < polygon.numPointsPerHole[holeIndex]; i++)
                {
                    if (polygon.GetHolePoint(i, holeIndex).x > holeBridgePoint.x)
                    {
                        holeBridgePoint = polygon.GetHolePoint(i, holeIndex);
                        holeBridgeIndex = i;
                    }
                }
                sortedHoleData.Add(new HoleData(holeIndex, holeBridgeIndex, holeBridgePoint));
            }
            // Sort hole data so that holes furthest to the right are first
            sortedHoleData.Sort((x, y) => (x.bridgePoint.x > y.bridgePoint.x) ? -1 : 1);

            foreach (HoleData holeData in sortedHoleData)
            {
                // Find first edge which intersects with rightwards ray originating at the hole bridge point.
                Vector2 rayIntersectPoint = new Vector2(float.MaxValue, holeData.bridgePoint.y);
                List <LinkedListNode <Vertex> > hullNodesPotentiallyInBridgeTriangle = new List <LinkedListNode <Vertex> >();
                LinkedListNode <Vertex>         initialBridgeNodeOnHull = null;
                currentNode = vertexList.First;
                while (currentNode != null)
                {
                    LinkedListNode <Vertex> nextNode = (currentNode.Next == null) ? vertexList.First : currentNode.Next;
                    Vector2 p0 = currentNode.Value.position;
                    Vector2 p1 = nextNode.Value.position;

                    // at least one point must be to right of holeData.bridgePoint for intersection with ray to be possible
                    if (p0.x > holeData.bridgePoint.x || p1.x > holeData.bridgePoint.x)
                    {
                        // one point is above, one point is below
                        if (p0.y > holeData.bridgePoint.y != p1.y > holeData.bridgePoint.y)
                        {
                            float rayIntersectX = p1.x; // only true if line p0,p1 is vertical
                            if (!Mathf.Approximately(p0.x, p1.x))
                            {
                                float intersectY = holeData.bridgePoint.y;
                                float gradient   = (p0.y - p1.y) / (p0.x - p1.x);
                                float c          = p1.y - gradient * p1.x;
                                rayIntersectX = (intersectY - c) / gradient;
                            }

                            // intersection must be to right of bridge point
                            if (rayIntersectX > holeData.bridgePoint.x)
                            {
                                LinkedListNode <Vertex> potentialNewBridgeNode = (p0.x > p1.x) ? currentNode : nextNode;
                                // if two intersections occur at same x position this means is duplicate edge
                                // duplicate edges occur where a hole has been joined to the outer polygon
                                bool isDuplicateEdge = Mathf.Approximately(rayIntersectX, rayIntersectPoint.x);

                                // connect to duplicate edge (the one that leads away from the other, already connected hole, and back to the original hull) if the
                                // current hole's bridge point is higher up than the bridge point of the other hole (so that the new bridge connection doesn't intersect).
                                bool connectToThisDuplicateEdge = holeData.bridgePoint.y > potentialNewBridgeNode.Previous.Value.position.y;

                                if (!isDuplicateEdge || connectToThisDuplicateEdge)
                                {
                                    // if this is the closest ray intersection thus far, set bridge hull node to point in line having greater x pos (since def to right of hole).
                                    if (rayIntersectX < rayIntersectPoint.x || isDuplicateEdge)
                                    {
                                        rayIntersectPoint.x     = rayIntersectX;
                                        initialBridgeNodeOnHull = potentialNewBridgeNode;
                                    }
                                }
                            }
                        }
                    }

                    // Determine if current node might lie inside the triangle formed by holeBridgePoint, rayIntersection, and bridgeNodeOnHull
                    // We only need consider those which are reflex, since only these will be candidates for visibility from holeBridgePoint.
                    // A list of these nodes is kept so that in next step it is not necessary to iterate over all nodes again.
                    if (currentNode != initialBridgeNodeOnHull)
                    {
                        if (!currentNode.Value.isConvex && p0.x > holeData.bridgePoint.x)
                        {
                            hullNodesPotentiallyInBridgeTriangle.Add(currentNode);
                        }
                    }
                    currentNode = currentNode.Next;
                }

                // Check triangle formed by hullBridgePoint, rayIntersection, and bridgeNodeOnHull.
                // If this triangle contains any points, those points compete to become new bridgeNodeOnHull
                LinkedListNode <Vertex> validBridgeNodeOnHull = initialBridgeNodeOnHull;
                foreach (LinkedListNode <Vertex> nodePotentiallyInTriangle in hullNodesPotentiallyInBridgeTriangle)
                {
                    if (nodePotentiallyInTriangle.Value.index == initialBridgeNodeOnHull.Value.index)
                    {
                        continue;
                    }
                    // if there is a point inside triangle, this invalidates the current bridge node on hull.
                    if (Maths2D.PointInTriangle(holeData.bridgePoint, rayIntersectPoint, initialBridgeNodeOnHull.Value.position, nodePotentiallyInTriangle.Value.position))
                    {
                        // Duplicate points occur at hole and hull bridge points.
                        bool isDuplicatePoint = validBridgeNodeOnHull.Value.position == nodePotentiallyInTriangle.Value.position;

                        // if multiple nodes inside triangle, we want to choose the one with smallest angle from holeBridgeNode.
                        // if is a duplicate point, then use the one occurring later in the list
                        float currentDstFromHoleBridgeY    = Mathf.Abs(holeData.bridgePoint.y - validBridgeNodeOnHull.Value.position.y);
                        float pointInTriDstFromHoleBridgeY = Mathf.Abs(holeData.bridgePoint.y - nodePotentiallyInTriangle.Value.position.y);

                        if (pointInTriDstFromHoleBridgeY < currentDstFromHoleBridgeY || isDuplicatePoint)
                        {
                            validBridgeNodeOnHull = nodePotentiallyInTriangle;
                        }
                    }
                }

                // Insert hole points (starting at holeBridgeNode) into vertex list at validBridgeNodeOnHull
                currentNode = validBridgeNodeOnHull;
                for (int i = holeData.bridgeIndex; i <= polygon.numPointsPerHole[holeData.holeIndex] + holeData.bridgeIndex; i++)
                {
                    int previousIndex = currentNode.Value.index;
                    int currentIndex  = polygon.IndexOfPointInHole(i % polygon.numPointsPerHole[holeData.holeIndex], holeData.holeIndex);
                    int nextIndex     = polygon.IndexOfPointInHole((i + 1) % polygon.numPointsPerHole[holeData.holeIndex], holeData.holeIndex);

                    if (i == polygon.numPointsPerHole[holeData.holeIndex] + holeData.bridgeIndex) // have come back to starting point
                    {
                        nextIndex = validBridgeNodeOnHull.Value.index;                            // next point is back to the point on the hull
                    }

                    bool   vertexIsConvex = IsConvex(polygon.points[previousIndex], polygon.points[currentIndex], polygon.points[nextIndex]);
                    Vertex holeVertex     = new Vertex(polygon.points[currentIndex], currentIndex, vertexIsConvex);
                    currentNode = vertexList.AddAfter(currentNode, holeVertex);
                }

                // Add duplicate hull bridge vert now that we've come all the way around. Also set its concavity
                Vector2 nextVertexPos       = (currentNode.Next == null) ? vertexList.First.Value.position : currentNode.Next.Value.position;
                bool    isConvex            = IsConvex(holeData.bridgePoint, validBridgeNodeOnHull.Value.position, nextVertexPos);
                Vertex  repeatStartHullVert = new Vertex(validBridgeNodeOnHull.Value.position, validBridgeNodeOnHull.Value.index, isConvex);
                vertexList.AddAfter(currentNode, repeatStartHullVert);

                //Set concavity of initial hull bridge vert, since it may have changed now that it leads to hole vert
                LinkedListNode <Vertex> nodeBeforeStartBridgeNodeOnHull = (validBridgeNodeOnHull.Previous == null) ? vertexList.Last : validBridgeNodeOnHull.Previous;
                LinkedListNode <Vertex> nodeAfterStartBridgeNodeOnHull  = (validBridgeNodeOnHull.Next == null) ? vertexList.First : validBridgeNodeOnHull.Next;
                validBridgeNodeOnHull.Value.isConvex = IsConvex(nodeBeforeStartBridgeNodeOnHull.Value.position, validBridgeNodeOnHull.Value.position, nodeAfterStartBridgeNodeOnHull.Value.position);
            }
            return(vertexList);
        }
예제 #37
0
        /// <summary>
        /// use the IComparer interface of an item to insert that item into the
        /// linked list in an ordered sequence.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="List"></param>
        /// <param name="InsertItem"></param>
        /// <param name="CurrentNode"></param>
        /// <returns></returns>
        public static LinkedListNode <T> OrderedListInsert <T>(
            this LinkedList <T> List, T InsertItem, LinkedListNode <T> CurrentNode)
            where T : IComparer <T>
        {
            LinkedListNode <T> insertedNode = null;
            LinkedListNode <T> baseNode     = null;

            // start the search for the ordered insert position at the CurrentNode.
            var startNode = CurrentNode;

            if (startNode == null)
            {
                startNode = List.First;
            }

            // search forward for the insert after node.
            var node = startNode;
            LinkedListNode <T> pvNode = null;

            while (true)
            {
                if (node == null)
                {
                    baseNode = pvNode;
                    break;
                }

                var rc = InsertItem.Compare(InsertItem, node.Value);

                // insert item is before the current item. If there is a pvNode,
                // then setup to insert after the pvNode.
                if (rc == -1)
                {
                    baseNode = pvNode;
                    break;
                }

                pvNode = node;
                node   = node.Next;
            }

            // search backward for the insert after node.
            if (baseNode == null)
            {
                node = startNode;
                while (true)
                {
                    if (node == null)
                    {
                        baseNode = null;
                        break;
                    }

                    var rc = InsertItem.Compare(InsertItem, node.Value);

                    // insert item is equal or after the current item.
                    // Setup to insert after this current item.
                    if ((rc == 0) || (rc == 1))
                    {
                        baseNode = node;
                        break;
                    }

                    node = node.Previous;
                }
            }

            // insert after the base node.
            if (baseNode != null)
            {
                insertedNode = List.AddAfter(baseNode, InsertItem);
            }
            else
            {
                insertedNode = List.AddFirst(InsertItem);
            }

            return(insertedNode);
        }
예제 #38
0
        public static IList <int> PlayCrabCups(
            IList <int> startingNumbers,
            int numberOfCupsToPickUp,
            int numberOfRounds)
        {
            var numberLinkedList      = new LinkedList <int>(startingNumbers);
            var labelToNodeDictionary = new Dictionary <int, LinkedListNode <int> >();
            var currentNode           = numberLinkedList.First;

            for (var i = 0; i < startingNumbers.Count; i++)
            {
                if (currentNode == null)
                {
                    continue;
                }
                labelToNodeDictionary.Add(currentNode.Value, currentNode);
                currentNode = currentNode.Next;
            }

            var currentCupNode = numberLinkedList.First;

            //var startTime = DateTime.Now;
            //const int pingRounds = 1000000;
            for (var roundNumber = 1; roundNumber <= numberOfRounds; roundNumber++)
            {
                var cupsToRemoveNodes = new List <LinkedListNode <int> >();

                //if (roundNumber % pingRounds == 0)
                //{
                //    var endTime = DateTime.Now;
                //    //var timeDiffSeconds = (endTime - startTime).TotalSeconds;
                //    //var secondsPerRound = (double)timeDiffSeconds / pingRounds;
                //    //var totalSeconds = numberOfRounds * secondsPerRound;
                //    //Console.WriteLine($"---> Round {roundNumber}: {timeDiffSeconds} seconds; Estimated total time for all: {totalSeconds}");
                //    startTime = DateTime.Now;
                //}

                var nextCupNode = currentCupNode;
                for (var i = 0; i < numberOfCupsToPickUp; i++)
                {
                    nextCupNode = nextCupNode?.Next ?? numberLinkedList.First;
                    cupsToRemoveNodes.Add(nextCupNode);
                }

                if (currentCupNode != null)
                {
                    var destinationCup = currentCupNode.Value;
                    for (var i = 1; i < startingNumbers.Count; i++)
                    {
                        destinationCup--;
                        if (destinationCup < 1)
                        {
                            destinationCup += startingNumbers.Count;
                        }
                        if (!cupsToRemoveNodes.Select(n => n.Value).Contains(destinationCup))
                        {
                            break;
                        }
                    }

                    var destinationCupNode = labelToNodeDictionary[destinationCup];

                    // Remove them
                    foreach (var removeNode in cupsToRemoveNodes)
                    {
                        numberLinkedList.Remove(removeNode);
                    }

                    var addAfterNode = destinationCupNode;
                    foreach (var addNode in cupsToRemoveNodes)
                    {
                        numberLinkedList.AddAfter(addAfterNode, addNode);
                        addAfterNode = addNode;
                    }
                }

                currentCupNode = currentCupNode?.Next ?? numberLinkedList.First;
            }

            return(numberLinkedList.ToList());
        }
예제 #39
0
        static void Main(string[] args)
        {
            Random           r = new Random();
            LinkedList <int> l = new LinkedList <int>();

            for (int i = 0; i < 10; ++i)
            {
                if (r.Next(2) == 0)
                {
                    l.AddLast(i);
                }
                else
                {
                    l.AddFirst(i);
                }
            }

            //Print list from manager class
            foreach (int i in l)
            {
                Console.Write($"{i} ");
            }
            Console.WriteLine();

            LinkedListNode <int> second = null;

            //Add as third node (manual traversal)
            if (l.Count >= 2)
            {
                second = l.First.Next;
                l.AddAfter(second, 99);
            }


            List <int> li = l.ToList();


            LinkedListNode <int> n = l.First;

            if (!(n is null))
            {
                do
                {
                    Console.Write($"{n.Value} ");
                    n = n.Next;
                }while (n != null);
            }
            Console.WriteLine();


            Stack <LinkedList <int> > slli = new Stack <LinkedList <int> >();

            for (int i = 0; i < 10; ++i)
            {
                LinkedList <int> lli = new LinkedList <int>();
                for (int j = 0; j < i; ++j)
                {
                    lli.AddFirst(r.Next(10));
                }
                slli.Push(lli);
            }

            while (slli.Count > 0)
            {
                LinkedList <int> lli = slli.Pop();
                foreach (int x in lli)
                {
                    Console.Write($"{x} ");
                }
            }

            Console.ReadKey();
        }
예제 #40
0
    public static void Main()
    {
        // <Snippet2>
        // Create the link list.
        string[] words =
        { "the", "fox", "jumped", "over", "the", "dog" };
        LinkedList <string> sentence = new LinkedList <string>(words);

        Display(sentence, "The linked list values:");
        Console.WriteLine("sentence.Contains(\"jumped\") = {0}",
                          sentence.Contains("jumped"));
        // </Snippet2>

        // Add the word 'today' to the beginning of the linked list.
        sentence.AddFirst("today");
        Display(sentence, "Test 1: Add 'today' to beginning of the list:");

        // <Snippet3>
        // Move the first node to be the last node.
        LinkedListNode <string> mark1 = sentence.First;

        sentence.RemoveFirst();
        sentence.AddLast(mark1);
        // </Snippet3>
        Display(sentence, "Test 2: Move first node to be last node:");

        // Change the last node be 'yesterday'.
        sentence.RemoveLast();
        sentence.AddLast("yesterday");
        Display(sentence, "Test 3: Change the last node to 'yesterday':");

        // <Snippet4>
        // Move the last node to be the first node.
        mark1 = sentence.Last;
        sentence.RemoveLast();
        sentence.AddFirst(mark1);
        // </Snippet4>
        Display(sentence, "Test 4: Move last node to be first node:");


        // <Snippet12>
        // Indicate, by using parentheisis, the last occurence of 'the'.
        sentence.RemoveFirst();
        LinkedListNode <string> current = sentence.FindLast("the");

        // </Snippet12>
        IndicateNode(current, "Test 5: Indicate last occurence of 'the':");

        // <Snippet5>
        // Add 'lazy' and 'old' after 'the' (the LinkedListNode named current).
        sentence.AddAfter(current, "old");
        sentence.AddAfter(current, "lazy");
        // </Snippet5>
        IndicateNode(current, "Test 6: Add 'lazy' and 'old' after 'the':");

        // <Snippet6>
        // Indicate 'fox' node.
        current = sentence.Find("fox");
        IndicateNode(current, "Test 7: Indicate the 'fox' node:");

        // Add 'quick' and 'brown' before 'fox':
        sentence.AddBefore(current, "quick");
        sentence.AddBefore(current, "brown");
        // </Snippet6>
        IndicateNode(current, "Test 8: Add 'quick' and 'brown' before 'fox':");

        // Keep a reference to the current node, 'fox',
        // and to the previous node in the list. Indicate the 'dog' node.
        mark1 = current;
        LinkedListNode <string> mark2 = current.Previous;

        current = sentence.Find("dog");
        IndicateNode(current, "Test 9: Indicate the 'dog' node:");

        // The AddBefore method throws an InvalidOperationException
        // if you try to add a node that already belongs to a list.
        Console.WriteLine("Test 10: Throw exception by adding node (fox) already in the list:");
        try
        {
            sentence.AddBefore(current, mark1);
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine("Exception message: {0}", ex.Message);
        }
        Console.WriteLine();

        // <Snippet7>
        // Remove the node referred to by mark1, and then add it
        // before the node referred to by current.
        // Indicate the node referred to by current.
        sentence.Remove(mark1);
        sentence.AddBefore(current, mark1);
        // </Snippet7>
        IndicateNode(current, "Test 11: Move a referenced node (fox) before the current node (dog):");

        // <Snippet8>
        // Remove the node referred to by current.
        sentence.Remove(current);
        // </Snippet8>
        IndicateNode(current, "Test 12: Remove current node (dog) and attempt to indicate it:");

        // Add the node after the node referred to by mark2.
        sentence.AddAfter(mark2, current);
        IndicateNode(current, "Test 13: Add node removed in test 11 after a referenced node (brown):");

        // The Remove method finds and removes the
        // first node that that has the specified value.
        sentence.Remove("old");
        Display(sentence, "Test 14: Remove node that has the value 'old':");

        // <Snippet9>
        // When the linked list is cast to ICollection(Of String),
        // the Add method adds a node to the end of the list.
        sentence.RemoveLast();
        ICollection <string> icoll = sentence;

        icoll.Add("rhinoceros");
        // </Snippet9>
        Display(sentence, "Test 15: Remove last node, cast to ICollection, and add 'rhinoceros':");

        Console.WriteLine("Test 16: Copy the list to an array:");
        //<Snippet10>
        // Create an array with the same number of
        // elements as the inked list.
        string[] sArray = new string[sentence.Count];
        sentence.CopyTo(sArray, 0);

        foreach (string s in sArray)
        {
            Console.WriteLine(s);
        }
        //</Snippet10>

        //<Snippet11>
        // Release all the nodes.
        sentence.Clear();

        Console.WriteLine();
        Console.WriteLine("Test 17: Clear linked list. Contains 'jumped' = {0}",
                          sentence.Contains("jumped"));
        //</Snippet11>

        Console.ReadLine();
    }
 static LinkedListDemo()
 {
     linkList.AddFirst("h1");
     linkList.AddAfter(linkList.Find("h1"), "h2");
     linkList.AddBefore(linkList.Find("h2"), "h3");
 }
 public void InsertChildAfter(RenderElement parent, RenderElement after, RenderElement re)
 {
     re._internalLinkedNode = _myElements.AddAfter(after._internalLinkedNode, re);
     RenderElement.SetParentLink(re, parent);
     re.InvalidateGraphics();
 }
예제 #43
0
        private void AddApparelToLinkedList(Apparel apparel, LinkedList <Apparel> l)
        {
            if (!l.Contains(apparel))
            {
                float score = JobGiver_OptimizeApparel.ApparelScoreRaw(null, apparel);
                for (LinkedListNode <Apparel> n = l.First; n != null; n = n.Next)
                {
                    float nScore = JobGiver_OptimizeApparel.ApparelScoreRaw(null, apparel);
                    if (score >= nScore)
                    {
                        l.AddBefore(n, apparel);
                        return;
                    }
                    else if (score < nScore)
                    {
                        l.AddAfter(n, apparel);
                        return;
                    }
                }
                l.AddLast(apparel);
            }

            /*
             #if TRACE
             * Log.Message("Start StoredApparel.AddApparelToLinkedList");
             * Log.Warning("Apparel: " + apparel.Label);
             * StringBuilder sb = new StringBuilder("LinkedList: ");
             * foreach (Apparel a in l)
             * {
             *  sb.Append(a.LabelShort);
             *  sb.Append(", ");
             * }
             * Log.Warning(sb.ToString());
             #endif
             * QualityCategory q;
             * if (!apparel.TryGetQuality(out q))
             * {
             #if TRACE
             *  Log.Message("AddLast - quality not found");
             #endif
             *  l.AddLast(apparel);
             * }
             * else
             * {
             #if TRACE
             *  Log.Message("HP: " + apparel.HitPoints + " HPMax: " + apparel.MaxHitPoints);
             #endif
             *  int hpPercent = apparel.HitPoints / apparel.MaxHitPoints;
             *  for (LinkedListNode<Apparel> n = l.First; n != null; n = n.Next)
             *  {
             *      QualityCategory nq;
             *      if (!n.Value.TryGetQuality(out nq) ||
             *          q > nq ||
             *          (q == nq && hpPercent >= (n.Value.HitPoints / n.Value.MaxHitPoints)))
             *      {
             *          l.AddBefore(n, apparel);
             *          return;
             *      }
             *  }
             *  l.AddLast(apparel);
             * }
             #if TRACE
             * Log.Message("End StoredApparel.AddApparelToLinkedList");
             #endif
             */
        }
예제 #44
0
        private void InsertBlock(
            long BasePosition,
            long PagesCount,
            MemoryState OldState,
            MemoryPermission OldPermission,
            MemoryAttribute OldAttribute,
            MemoryState NewState,
            MemoryPermission NewPermission,
            MemoryAttribute NewAttribute)
        {
            //Insert new block on the list only on areas where the state
            //of the block matches the state specified on the Old* state
            //arguments, otherwise leave it as is.
            OldAttribute |= MemoryAttribute.IpcAndDeviceMapped;

            ulong Start = (ulong)BasePosition;
            ulong End   = (ulong)PagesCount * PageSize + Start;

            LinkedListNode <KMemoryBlock> Node = Blocks.First;

            while (Node != null)
            {
                LinkedListNode <KMemoryBlock> NewNode  = Node;
                LinkedListNode <KMemoryBlock> NextNode = Node.Next;

                KMemoryBlock CurrBlock = Node.Value;

                ulong CurrStart = (ulong)CurrBlock.BasePosition;
                ulong CurrEnd   = (ulong)CurrBlock.PagesCount * PageSize + CurrStart;

                if (Start < CurrEnd && CurrStart < End)
                {
                    MemoryAttribute CurrBlockAttr = CurrBlock.Attribute | MemoryAttribute.IpcAndDeviceMapped;

                    if (CurrBlock.State != OldState ||
                        CurrBlock.Permission != OldPermission ||
                        CurrBlockAttr != OldAttribute)
                    {
                        Node = NextNode;

                        continue;
                    }

                    if (CurrStart >= Start && CurrEnd <= End)
                    {
                        CurrBlock.State      = NewState;
                        CurrBlock.Permission = NewPermission;
                        CurrBlock.Attribute &= ~MemoryAttribute.IpcAndDeviceMapped;
                        CurrBlock.Attribute |= NewAttribute;
                    }
                    else if (CurrStart >= Start)
                    {
                        CurrBlock.BasePosition = (long)End;

                        CurrBlock.PagesCount = (long)((CurrEnd - End) / PageSize);

                        long NewPagesCount = (long)((End - CurrStart) / PageSize);

                        NewNode = Blocks.AddBefore(Node, new KMemoryBlock(
                                                       (long)CurrStart,
                                                       NewPagesCount,
                                                       NewState,
                                                       NewPermission,
                                                       NewAttribute));
                    }
                    else if (CurrEnd <= End)
                    {
                        CurrBlock.PagesCount = (long)((Start - CurrStart) / PageSize);

                        long NewPagesCount = (long)((CurrEnd - Start) / PageSize);

                        NewNode = Blocks.AddAfter(Node, new KMemoryBlock(
                                                      BasePosition,
                                                      NewPagesCount,
                                                      NewState,
                                                      NewPermission,
                                                      NewAttribute));
                    }
                    else
                    {
                        CurrBlock.PagesCount = (long)((Start - CurrStart) / PageSize);

                        long NextPagesCount = (long)((CurrEnd - End) / PageSize);

                        NewNode = Blocks.AddAfter(Node, new KMemoryBlock(
                                                      BasePosition,
                                                      PagesCount,
                                                      NewState,
                                                      NewPermission,
                                                      NewAttribute));

                        Blocks.AddAfter(NewNode, new KMemoryBlock(
                                            (long)End,
                                            NextPagesCount,
                                            CurrBlock.State,
                                            CurrBlock.Permission,
                                            CurrBlock.Attribute));

                        NextNode = null;
                    }

                    MergeEqualStateNeighbours(NewNode);
                }

                Node = NextNode;
            }
        }
        static void Main()
        {
            LinkedList <String> list = new LinkedList <String>();

            list.AddLast("one");
            list.AddLast("two");
            list.AddLast("three");
            list.AddLast("four");
            list.AddLast("five");
            list.AddLast("six");
            list.AddLast("seven");
            Console.WriteLine("-------elements in the linkedlist---------------");
            foreach (var st in list)
            {
                Console.WriteLine(st);
            }
            Console.WriteLine("--------------using Enumerator-------------------");
            LinkedList <string> .Enumerator ll = list.GetEnumerator();
            while (ll.MoveNext())
            {
                Console.WriteLine(ll.Current);
            }
            Console.WriteLine("remove paricualr element-------------------");
            list.Remove("one");
            foreach (var e in list)
            {
                Console.WriteLine(e);
            }
            Console.WriteLine("remove at first-------------------------");
            list.RemoveFirst();
            foreach (var e in list)
            {
                Console.WriteLine(e);
            }
            Console.WriteLine("Removes at last------------------------------");
            list.RemoveLast();
            foreach (var e in list)
            {
                Console.WriteLine(e);
            }
            Console.WriteLine("Add at first---------------------------------");
            list.AddFirst("hello");
            foreach (var e in list)
            {
                Console.WriteLine(e);
            }
            Console.WriteLine("add at last---------------------------------");
            list.AddLast("Sravss");
            foreach (var e in list)
            {
                Console.WriteLine(e);
            }
            var newNode = list.AddLast("Brad");

            list.AddBefore(newNode, "wowo super");
            Console.WriteLine("LinkedList after adding new nodes...");
            foreach (var stu in list)
            {
                Console.WriteLine(stu);
            }
            var newNode1 = list.AddFirst("welcome");

            list.AddAfter(newNode1, "zensarians");
            Console.WriteLine("LinkedList after adding new nodes...");
            foreach (var stu in list)
            {
                Console.WriteLine(stu);
            }
            Console.WriteLine("using find()--------------------------");

            LinkedListNode <string> temp = list.Find("hello");

            Console.WriteLine(temp.Value);
        }
        public static void Show()
        {
            //1 内存连续存储,节约空间,可以索引访问,读取快,增删慢

            #region Array
            {
                //Array:在内存上连续分配的,而且元素类型是一样的
                //可以坐标访问  读取快--增删慢,长度不变
                Console.WriteLine("***************Array******************");
                int[] intArray = new int[3];
                intArray[0] = 123;
                string[] stringArray = new string[] { "123", "234" };//Array
            }
            {
                //ArrayList  不定长的,连续分配的;
                //元素没有类型限制,任何元素都是当成object处理,如果是值类型,会有装箱操作
                //读取快--增删慢
                Console.WriteLine("***************ArrayList******************");
                ArrayList arrayList = new ArrayList();
                arrayList.Add("Eleven");
                arrayList.Add("Is");
                arrayList.Add(32);//add增加长度
                //arrayList[4] = 26;//索引复制,不会增加长度
                //删除数据
                //arrayList.RemoveAt(4);
                var value = arrayList[2];
                arrayList.RemoveAt(0);
                arrayList.Remove("Eleven");
            }
            {
                //List:也是Array,内存上都是连续摆放;不定长;泛型,保证类型安全,避免装箱拆箱
                //读取快--增删慢
                Console.WriteLine("***************List<T>******************");
                List <int> intList = new List <int>()
                {
                    1, 2, 3, 4
                };
                intList.Add(123);
                intList.Add(123);
                //intList.Add("123");
                //intList[0] = 123;
                List <string> stringList = new List <string>();
                //stringList[0] = "123";//异常的
                foreach (var item in intList)
                {
                }
            }
            #endregion

            //2 非连续摆放,存储数据+地址,找数据的话就只能顺序查找,读取慢;增删快,
            #region 链表
            {
                //LinkedList:泛型的特点;链表,元素不连续分配,每个元素都有记录前后节点
                //节点值可以重复
                //能不能下标访问?不能,找元素就只能遍历  查找不方便
                //增删 就比较方便
                Console.WriteLine("***************LinkedList<T>******************");
                LinkedList <int> linkedList = new LinkedList <int>();
                //linkedList[3]
                linkedList.AddFirst(123);
                linkedList.AddLast(456);

                bool isContain = linkedList.Contains(123);
                LinkedListNode <int> node123 = linkedList.Find(123);  //元素123的位置  从头查找
                linkedList.AddBefore(node123, 123);
                linkedList.AddBefore(node123, 123);
                linkedList.AddAfter(node123, 9);

                linkedList.Remove(456);
                linkedList.Remove(node123);
                linkedList.RemoveFirst();
                linkedList.RemoveLast();
                linkedList.Clear();
            }

            {
                //Queue 就是链表  先进先出  放任务延迟执行,A不断写入日志任务  B不断获取任务去执行
                Console.WriteLine("***************Queue<T>******************");
                Queue <string> numbers = new Queue <string>();
                numbers.Enqueue("one");
                numbers.Enqueue("two");
                numbers.Enqueue("three");
                numbers.Enqueue("four");
                numbers.Enqueue("four");
                numbers.Enqueue("five");

                foreach (string number in numbers)
                {
                    Console.WriteLine(number);
                }

                Console.WriteLine($"Dequeuing '{numbers.Dequeue()}'");
                Console.WriteLine($"Peek at next item to dequeue: { numbers.Peek()}");
                Console.WriteLine($"Dequeuing '{numbers.Dequeue()}'");

                Queue <string> queueCopy = new Queue <string>(numbers.ToArray());
                foreach (string number in queueCopy)
                {
                    Console.WriteLine(number);
                }

                Console.WriteLine($"queueCopy.Contains(\"four\") = {queueCopy.Contains("four")}");
                queueCopy.Clear();
                Console.WriteLine($"queueCopy.Count = {queueCopy.Count}");
            }
            //队列是没瓶底的瓶子,栈是有瓶底的瓶子
            {
                //Stack 就是链表  先进后出  解析表达式目录树的时候,先产生的数据后使用
                //操作记录为命令,撤销的时候是倒序的
                Console.WriteLine("***************Stack<T>******************");
                Stack <string> numbers = new Stack <string>();
                numbers.Push("one");
                numbers.Push("two");
                numbers.Push("three");
                numbers.Push("four");
                numbers.Push("five");//放进去

                foreach (string number in numbers)
                {
                    Console.WriteLine(number);
                }

                Console.WriteLine($"Pop '{numbers.Pop()}'");                           //获取并移除
                Console.WriteLine($"Peek at next item to dequeue: { numbers.Peek()}"); //获取不移除
                Console.WriteLine($"Pop '{numbers.Pop()}'");

                Stack <string> stackCopy = new Stack <string>(numbers.ToArray());
                foreach (string number in stackCopy)
                {
                    Console.WriteLine(number);
                }

                Console.WriteLine($"stackCopy.Contains(\"four\") = {stackCopy.Contains("four")}");
                stackCopy.Clear();
                Console.WriteLine($"stackCopy.Count = {stackCopy.Count}");
            }
            #endregion

            //set纯粹的集合,容器,东西丢进去,唯一性 无序的

            #region Set
            {
                //集合:hash分布,元素间没关系,动态增加容量  去重
                //统计用户IP;IP投票   交叉并补--二次好友/间接关注/粉丝合集
                Console.WriteLine("***************HashSet<string>******************");
                HashSet <string> hashSet = new HashSet <string>();
                hashSet.Add("123");
                hashSet.Add("689");
                hashSet.Add("456");
                hashSet.Add("12435");
                hashSet.Add("12435");
                hashSet.Add("12435");
                //hashSet[0];
                foreach (var item in hashSet)
                {
                    Console.WriteLine(item);
                }
                Console.WriteLine(hashSet.Count);
                Console.WriteLine(hashSet.Contains("12345"));

                {
                    HashSet <string> hashSet1 = new HashSet <string>();
                    hashSet1.Add("123");
                    hashSet1.Add("689");
                    hashSet1.Add("789");
                    hashSet1.Add("12435");
                    hashSet1.Add("12435");
                    hashSet1.Add("12435");
                    hashSet1.SymmetricExceptWith(hashSet); //补
                    hashSet1.UnionWith(hashSet);           //并
                    hashSet1.ExceptWith(hashSet);          //差
                    hashSet1.IntersectWith(hashSet);       //交
                    //风--亡五  找出共同的好友
                }
                hashSet.ToList();
                hashSet.Clear();
            }

            {
                //排序的集合:去重  而且排序
                //统计排名--每统计一个就丢进去集合
                Console.WriteLine("***************SortedSet<string>******************");
                SortedSet <string> sortedSet = new SortedSet <string>();
                //IComparer<T> comparer  自定义对象要排序,就用这个指定
                sortedSet.Add("123");
                sortedSet.Add("689");
                sortedSet.Add("456");
                sortedSet.Add("12435");
                sortedSet.Add("12435");
                sortedSet.Add("12435");

                foreach (var item in sortedSet)
                {
                    Console.WriteLine(item);
                }
                Console.WriteLine(sortedSet.Count);
                Console.WriteLine(sortedSet.Contains("12345"));
                {
                    SortedSet <string> sortedSet1 = new SortedSet <string>();
                    sortedSet1.Add("123");
                    sortedSet1.Add("689");
                    sortedSet1.Add("456");
                    sortedSet1.Add("12435");
                    sortedSet1.Add("12435");
                    sortedSet1.Add("12435");
                    sortedSet1.SymmetricExceptWith(sortedSet); //补
                    sortedSet1.UnionWith(sortedSet);           //并
                    sortedSet1.ExceptWith(sortedSet);          //差
                    sortedSet1.IntersectWith(sortedSet);       //交
                }

                sortedSet.ToList();
                sortedSet.Clear();
            }
            #endregion

            //读取&增删都快? 有 hash散列 字典
            //key-value,一段连续有限空间放value(开辟的空间比用到的多,hash是用空间换性能),基于key散列计算得到地址索引,这样读取快
            //增删也快,删除时也是计算位置,增加也不影响别人
            //肯定会出现2个key(散列冲突),散列结果一致18,可以让第二次的+1,
            //可能会造成效率的降低,尤其是数据量大的情况下,以前测试过dictionary在3w条左右性能就开始下降的厉害
            #region key-value
            {
                //Hashtable key-value  体积可以动态增加 拿着key计算一个地址,然后放入key - value
                //object-装箱拆箱  如果不同的key得到相同的地址,第二个在前面地址上 + 1
                //查找的时候,如果地址对应数据的key不对,那就 + 1查找。。
                //浪费了空间,Hashtable是基于数组实现
                //查找个数据  一次定位; 增删 一次定位;  增删查改 都很快
                //浪费空间,数据太多,重复定位定位,效率就下去了
                Console.WriteLine("***************Hashtable******************");
                Hashtable table = new Hashtable();
                table.Add("123", "456");
                table[234]      = 456;
                table[234]      = 567;
                table[32]       = 4562;
                table[1]        = 456;
                table["eleven"] = 456;
                foreach (DictionaryEntry objDE in table)
                {
                    Console.WriteLine(objDE.Key.ToString());
                    Console.WriteLine(objDE.Value.ToString());
                }
                //线程安全
                Hashtable.Synchronized(table);//只有一个线程写  多个线程读
            }
            {
                //字典:泛型;key - value,增删查改 都很快;有序的
                //  字典不是线程安全 ConcurrentDictionary
                Console.WriteLine("***************Dictionary******************");
                Dictionary <int, string> dic = new Dictionary <int, string>();
                dic.Add(1, "HaHa");
                dic.Add(5, "HoHo");
                dic.Add(3, "HeHe");
                dic.Add(2, "HiHi");
                dic.Add(4, "HuHu1");
                dic[4] = "HuHu";
                dic.Add(4, "HuHu");
                foreach (var item in dic)
                {
                    Console.WriteLine($"Key:{item.Key}, Value:{item.Value}");
                }
            }
            {
                Console.WriteLine("***************SortedDictionary******************");
                SortedDictionary <int, string> dic = new SortedDictionary <int, string>();
                dic.Add(1, "HaHa");
                dic.Add(5, "HoHo");
                dic.Add(3, "HeHe");
                dic.Add(2, "HiHi");
                dic.Add(4, "HuHu1");
                dic[4] = "HuHu";
                dic.Add(4, "HuHu");
                foreach (var item in dic)
                {
                    Console.WriteLine($"Key:{item.Key}, Value:{item.Value}");
                }
            }
            {
                //"a".GetHashCode();

                Console.WriteLine("***************SortedList******************");
                SortedList sortedList = new SortedList();//IComparer
                sortedList.Add("First", "Hello");
                sortedList.Add("Second", "World");
                sortedList.Add("Third", "!");

                sortedList["Third"] = "~~";    //
                sortedList.Add("Fourth", "!");
                sortedList.Add("Fourth", "!"); //重复的Key Add会错
                sortedList["Fourth"] = "!!!";
                var keyList   = sortedList.GetKeyList();
                var valueList = sortedList.GetValueList();

                sortedList.TrimToSize();//用于最小化集合的内存开销

                sortedList.Remove("Third");
                sortedList.RemoveAt(0);
                sortedList.Clear();
            }
            #endregion

            {
                //ConcurrentQueue 线程安全版本的Queue
                //ConcurrentStack线程安全版本的Stack
                //ConcurrentBag线程安全的对象集合
                //ConcurrentDictionary线程安全的Dictionary
                //BlockingCollection
            }
            {
                List <string> fruits =
                    new List <string> {
                    "apple", "passionfruit", "banana", "mango",
                    "orange", "blueberry", "grape", "strawberry"
                };

                IEnumerable <string> query = fruits.Where(fruit => fruit.Length < 6);
                foreach (var item in query)//遍历才会去查询比较   迭代器 yield
                {
                }

                IQueryable <string> queryable = fruits.AsQueryable <string>().Where(s => s.Length > 5);
                foreach (var item in queryable)//表达式目录树的解析,延迟到遍历的时候才去执行  EF的延迟查询
                {
                }
            }
        }
예제 #47
0
파일: Program.cs 프로젝트: NBuharin90/Tests
        static void Main(string[] args)
        {
            int elementsCount       = 10000000;
            var indexOfMiddle       = elementsCount / 2;
            int operationsCount     = 100;
            int longOperationsCount = 1000;

            //Коллекции
            var lst     = new List <int>();
            var linkLst = new LinkedList <int>();

            //Инициализация коллекций
            for (int i = 0; i < elementsCount; i++)
            {
                lst.Add(i);
                linkLst.AddLast(i);
            }

            //** Добавление в начало списка
            for (var i = 0; i < longOperationsCount; i++)       //551ms
            {
                lst.Insert(0, i);
            }
            for (var i = 0; i < operationsCount; i++)           //1349ms
            {
                linkLst.AddFirst(i);
            }

            //** Добавление в конец списка
            for (var i = 0; i < operationsCount; i++)           //70ms
            {
                lst.Add(i);
            }
            for (var i = 0; i < operationsCount; i++)           //1632ms
            {
                linkLst.AddLast(i);
            }

            int obj = 0;

            //** Операция чтения из середины списка
            for (var i = 0; i < operationsCount; i++)           //55ms
            {
                obj = lst[indexOfMiddle + i];
            }

            for (var i = 0; i < longOperationsCount; i++)      //3301ms
            {
                obj = linkLst.ElementAt(indexOfMiddle + i);
            }

            //** Добавление в середину списка
            //for (var i = 0; i < operationsCount; i++)                             //ms
            lst.Insert(indexOfMiddle, -1);                    //5ms
            //for (var i = 0; i < operationsCount; i++)                             //ms
            //{
            var obj1 = linkLst.Find(indexOfMiddle);               //18ms

            if (obj1 != null)
            {
                linkLst.AddAfter(obj1, -1);                       //1ms
            }
            //}

            Console.ReadKey();
        }
예제 #48
0
        static void Main()
        {
            LinkedList <string> myList = new LinkedList <string>();

            myList.AddLast("Pune");
            myList.AddLast("Mumbai");
            myList.AddLast("Kolhapur");
            myList.AddLast("Pandharpur");
            myList.AddLast("Satara");
            Console.WriteLine("Adding Nagpur at the first node using AddFirst()");
            myList.AddFirst("Nagpur");
            LinkedListNode <string> n1   = myList.Find("Mumbai");
            LinkedListNode <string> var1 = myList.AddAfter(n1, "Amravati");

            myList.AddBefore(var1, "Solapur");

            foreach (string str in myList)
            {
                Console.WriteLine(str);
            }
            Console.WriteLine("Iteration using GetEnumerator method");
            LinkedList <string> .Enumerator lle = myList.GetEnumerator();
            while (lle.MoveNext())
            {
                Console.WriteLine(lle.Current);
                //Console.WriteLine(lle.);
            }
            Console.WriteLine("Contains Method--------");
            bool ht = myList.Contains("Satara");

            Console.WriteLine(ht);
            Console.WriteLine("Using CopytTo method------------");
            string[] arr = new string[myList.Count];
            myList.CopyTo(arr, 0);
            foreach (string item in arr)
            {
                Console.WriteLine(item);
            }
            LinkedListNode <string> b = myList.FindLast("Pandharpur");

            Console.WriteLine("FindLast method:{0}", b.Value);
            bool rem = myList.Remove("Nagpur");

            Console.WriteLine("Removing Element Nagpur from the linked list:{0}", rem);
            foreach (string show in myList)
            {
                Console.WriteLine(show);
            }
            Console.WriteLine("Removing the starting node from the linked list");
            myList.RemoveFirst();
            foreach (string rem1 in myList)
            {
                Console.WriteLine(rem1);
            }
            Console.WriteLine("Removing the node at the last from the linked list");
            myList.RemoveLast();
            foreach (string disp in myList)
            {
                Console.WriteLine(disp);
            }
            //Console.WriteLine("Clearing the LinkedList");
            //myList.Clear();
            Console.Read();
        }
예제 #49
0
        /*
         * /// <summary>
         * /// check authentication attributes for the class
         * /// </summary>
         * protected virtual void MapClassAuth()
         * {
         *  object[] attributes = GetType().GetCustomAttributes(true);
         *  foreach (object attribute in attributes)
         *  {
         *      if (attribute.GetType() == typeof (AuthenticatorAttribute))
         *          AddAuthAttribute(ClassMethodName, attribute);
         *      if (attribute.GetType() == typeof (AuthenticationRequiredAttribute))
         *          AddCheckAuthAttribute(ClassMethodName, attribute);
         *  }
         * }
         */
        /// <summary>
        /// This method goes through all methods in the controller and
        /// add's them to a dictionary. They are later used to invoke
        /// the correct method depending on the url
        /// </summary>
        private void MapMethods()
        {
            lock (_methods)
            {
                // already mapped.
                if (_methods.Count > 0)
                {
                    return;
                }

                object[] controllerNameAttrs = GetType().GetCustomAttributes(typeof(ControllerNameAttribute), false);
                if (controllerNameAttrs.Length > 0)
                {
                    _controllerName = ((ControllerNameAttribute)controllerNameAttrs[0]).Name;
                }
                else
                {
                    _controllerName = GetType().Name;
                    if (ControllerName.Contains("Controller"))
                    {
                        _controllerName = ControllerName.Replace("Controller", "");
                    }
                    _controllerName = ControllerName.ToLower();
                }

                MethodInfo[] methods =
                    GetType().GetMethods(BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance);
                foreach (MethodInfo info in methods)
                {
                    ParameterInfo[] parameters = info.GetParameters();

                    // find regular render methods
                    if (parameters.Length == 0 && info.ReturnType == typeof(string))
                    {
                        string name = info.Name.ToLower();
                        if (name.Length > 3 && (name.Substring(0, 4) == "get_" || name.Substring(0, 4) == "set_"))
                        {
                            continue;
                        }
                        if (name == "tostring")
                        {
                            continue;
                        }

                        // Add authenticators
                        object[] authAttributes = info.GetCustomAttributes(true);
                        foreach (object attribute in authAttributes)
                        {
                            if (attribute.GetType() == typeof(AuthRequiredAttribute))
                            {
                                _authMethods.Add(info.Name.ToLower(), ((AuthRequiredAttribute)attribute).Level);
                            }
                        }
                        _methods.Add(info.Name.ToLower(), info);
                    }

                    // find raw handlers
                    object[] attributes = info.GetCustomAttributes(typeof(RawHandlerAttribute), true);
                    if (attributes.Length >= 1 && info.ReturnType == typeof(void) && parameters.Length == 0)
                    {
                        // Add authenticators
                        object[] authAttributes = info.GetCustomAttributes(true);
                        foreach (object attribute in authAttributes)
                        {
                            if (attribute.GetType() == typeof(AuthRequiredAttribute))
                            {
                                _authMethods.Add(info.Name.ToLower(), ((AuthRequiredAttribute)attribute).Level);
                            }
                        }
                        _binaryMethods.Add(info.Name.ToLower(), info);
                    }
                } //foreach

                methods = GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic);
                foreach (MethodInfo info in methods)
                {
                    ParameterInfo[] parameters = info.GetParameters();

                    // find before filters.
                    if (parameters.Length == 0 && info.ReturnType == typeof(bool))
                    {
                        object[] authAttributes = info.GetCustomAttributes(true);
                        foreach (object attribute in authAttributes)
                        {
                            if (attribute.GetType() == typeof(AuthValidatorAttribute))
                            {
                                if (_authValidator != null)
                                {
                                    throw new InvalidOperationException("Auth validator have already been specified.");
                                }
                                _authValidator = info;
                            }
                            else if (attribute.GetType() == typeof(BeforeFilterAttribute))
                            {
                                BeforeFilterAttribute       attr = (BeforeFilterAttribute)attribute;
                                LinkedListNode <MethodInfo> node = new LinkedListNode <MethodInfo>(info);


                                if (attr.Position == FilterPosition.First)
                                {
                                    _beforeFilters.AddFirst(node);
                                }
                                else if (attr.Position == FilterPosition.Last)
                                {
                                    _beforeFilters.AddLast(node);
                                }
                                else
                                {
                                    if (_lastMiddleFilter == null)
                                    {
                                        _beforeFilters.AddLast(node);
                                    }
                                    else
                                    {
                                        _beforeFilters.AddAfter(_lastMiddleFilter, node);
                                    }

                                    _lastMiddleFilter = node;
                                }
                            }
                        }
                    }
                }

                // Map index method.
                MethodInfo mi = GetType().GetMethod("Index", BindingFlags.Public | BindingFlags.Instance);
                if (mi != null && mi.ReturnType == typeof(string) && mi.GetParameters().Length == 0)
                {
                    DefaultMethod = "Index";
                }
            }
        }
예제 #50
0
        public LinkedListNode <WaypointEntry> InsertWaypointAfter(WaypointEntry entry, Vector3 pos, float orientation)
        {
            var newWp = CreateWaypoint(pos, orientation);

            return(Waypoints.AddAfter(entry.Node, newWp));
        }
예제 #51
0
        static void Main(string[] args)
        {
            //Imagine uma lista de frutas
            List <string> frutas = new List <string>
            {
                "abacate", "banana", "caqui", "damasco", "figo"
            };

            //Vamos imprimir essa lista
            foreach (var fruta in frutas)
            {
                Console.WriteLine(fruta);
            }
            Console.WriteLine();

            ///image1
            ///<image url="$(ProjectDir)\Slides\image1.png" scale=""/>
            //Adicionar um elemento ao final de uma lista é rápido

            //Porém inserir no meio da lista exige mais esforço computacional

            ///image2
            ///<image url="$(ProjectDir)\Slides\image2.png" scale=""/>
            //porque os elementos têm que ser deslocados para darem
            //espaço ao novo elemento!
            //E se tivermos que remover esse elemento, os elementos
            //seguintes precisam ser deslocados de novo!

            //Quanto maior a lista, mais ineficiente é a inserção
            //e remoção de elementos no meio dela!
            //Que coleção é apropriada para inserção/remoção rápida?

            //Apresentando LISTA LIGADA (LINKED LIST):
            //- Elementos não precisam estar em sequência em memória
            //- Cada elemento sabe quem é o anterior e o próximo
            //- Cada elemento é um "nó" que contém um valor

            ///linked
            ///<image url="$(ProjectDir)\Slides\linked.png" scale=""/>
            //Como a ordem é mantida? Usando ponteiros
            ///linked2
            ///<image url="$(ProjectDir)\Slides\linked2.png" scale=""/>
            //Instanciando uma nova lista ligada: dias da semana
            LinkedList <string> dias = new LinkedList <string>();
            //Adicionando um dia qualquer: "quarta"
            var d4 = dias.AddFirst("quarta");

            //"quarta" é o primeiro elemento da lista ligada
            ///image3
            ///<image url="$(ProjectDir)\Slides\image3.png" scale=""/>
            //cada elemento é um nó: LinkedListNode<T>
            ///System.Collections.Generic.LinkedListNode`1[System.String]

            //Mas e o valor "quarta"? Está na propriedade d4.Value
            Console.WriteLine("d4.Value: " + d4.Value);
            //E para adicionar mais itens? LinkedList não possui Add!
            //Podemos adicionar de 4 formas:
            //1. Como primeiró nó
            //2. Como último nó
            //3. Antes de um nó conhecido
            //4. Depois de um nó conhecido

            //Vamos adicionar segunda, antes de quarta:
            var d2 = dias.AddBefore(d4, "segunda");
            ///image4
            ///<image url="$(ProjectDir)\Slides\image4.png" scale=""/>
            //Agora d2 e d4 estão ligados!
            //- d2.Next é igual a d4
            //- d4.Previous é igual a d2
            //Continuando com nossa lista ligada,
            //vamos adicionar terça depois de segunda
            var d3 = dias.AddAfter(d2, "terça");
            ///image5
            ///<image url="$(ProjectDir)\Slides\image5.png" scale=""/>
            //Perceba que os "ponteiros", ou referências
            //de d2 e d4 foram redirecionados para d3!!
            //Vamos adicionar sexta depois de quarta
            var d6 = dias.AddAfter(d4, "sexta");
            ///image6
            ///<image url="$(ProjectDir)\Slides\image6.png" scale=""/>
            //sábado depois de sexta
            var d7 = dias.AddAfter(d6, "sábado");
            ///image7
            ///<image url="$(ProjectDir)\Slides\image7.png" scale=""/>
            //quinta antes de sexta
            var d5 = dias.AddBefore(d6, "quinta");
            ///image8
            ///<image url="$(ProjectDir)\Slides\image8.png" scale=""/>
            //domingo antes de segunda
            var d1 = dias.AddBefore(d2, "domingo");

            ///image9
            ///<image url="$(ProjectDir)\Slides\image9.png" scale=""/>
            //Agora vamos imprimir a lista ligada
            foreach (var dia in dias)
            {
                Console.WriteLine(dia);
            }
            Console.WriteLine();

            //LinkedList NÃO DÁ suporte ao acesso de índice: dias[0]
            //por isso podemos fazer um laço foreach mas não um for!
            var quarta = dias.Find("quarta");

            //Para removermos um elemento, podemos tanto
            //remover pelo valor quanto pela
            //referência do LinkedListNode
            //dias.Remove("quarta") ou dias.Remove(d4);
            dias.Remove("quarta");

            foreach (var dia in dias)
            {
                Console.WriteLine(dia);
            }
        }
예제 #52
0
 private void ReplaceInQueue(LinkedList<Element> queue, Element output, Element input)
 {
     queue.AddAfter(queue.Find(output), input);
     queue.Remove(output);
 }
예제 #53
0
        static void Main(string[] args)
        {
            //TAREFA 1: PRIMEIRO QUE ENTRA, PRIMEIRO QUE SAI (FIFO)

            var veiculo1 = "van";
            var veiculo2 = "kombi";
            var veiculo3 = "guincho";
            var veiculo4 = "pickup";

            Queue <string> pedagio = new Queue <string>();

            pedagio.Enqueue(veiculo1);
            pedagio.Enqueue(veiculo2);
            pedagio.Enqueue(veiculo3);
            pedagio.Enqueue(veiculo4);

            Console.WriteLine(pedagio.Dequeue());
            Console.WriteLine(pedagio.Dequeue());
            Console.WriteLine(pedagio.Dequeue());
            Console.WriteLine(pedagio.Dequeue());
            Console.WriteLine();

            //TAREFA 2: PRIMEIRO QUE ENTRA, ÚLTIMO QUE SAI (LIFO)

            string site0 = "<<vazio>>";
            string site1 = "google.com";
            string site2 = "caelum.com.br";
            string site3 = "alura.com.br";

            Stack <string> historicoNavegador = new Stack <string>();

            historicoNavegador.Push(site0);
            Console.WriteLine("Navegando para: {0}", site1);
            historicoNavegador.Push(site1);
            Console.WriteLine("Navegando para: {0}", site2);
            historicoNavegador.Push(site2);
            Console.WriteLine("Navegando para: {0}", site3);
            historicoNavegador.Push(site3);

            Console.WriteLine("Voltando para: {0}", historicoNavegador.Pop());
            Console.WriteLine("Voltando para: {0}", historicoNavegador.Pop());
            Console.WriteLine("Voltando para: {0}", historicoNavegador.Pop());
            Console.WriteLine("Voltando para: {0}", historicoNavegador.Pop());
            Console.WriteLine();

            //TAREFA 3: UMA COLEÇÃO PODEROSA

            List <string> meses = new List <string>
            {
                "janeiro", "fevereiro", "março", "abril",
                "abril", "maio", "junho",
                "julho", "agosto"
            };

            meses.Add("setembro");
            meses.AddRange(new string[] { "novembro", "dezembro", "onzembro" });

            meses.RemoveAt(4);
            meses.RemoveAt(meses.Count - 1);
            meses.Insert(9, "outubro");

            for (int i = 0; i < meses.Count; i++)
            {
                Console.WriteLine("mês {0}: {1}", i + 1, meses[i]);
            }
            Console.WriteLine();

            meses.Sort((m1, m2) => m1.CompareTo(m2));

            for (int i = 0; i < meses.Count; i++)
            {
                Console.WriteLine("{0}", meses[i]);
            }
            Console.WriteLine();

            //TAREFA 4: MATRIZ DE DADOS DE TAMANHO FIXO

            int[] imagem = new int[65535];

            int x = 31;
            int y = 14;

            const int rgb = 0x9EA3A7;

            imagem[27] = rgb;

            //TAREFA 5: LIGANDO OS NÓS

            LinkedList <string> dias = new LinkedList <string>();
            var d4 = dias.AddFirst("quarta");
            var d2 = dias.AddBefore(d4, "segunda");
            var d3 = dias.AddAfter(d2, "terça");
            var d6 = dias.AddAfter(d4, "sexta");
            var d7 = dias.AddAfter(d6, "sábado");
            var d5 = dias.AddBefore(d6, "quinta");
            var d1 = dias.AddBefore(d2, "domingo");

            foreach (var dia in dias)
            {
                Console.WriteLine(dia);
            }
            Console.WriteLine();

            //TAREFA 6: UNINDO COLEÇÕES SEM DUPLICAÇÃO

            var pares = new List <int> {
                0, 2, 4, 6, 8, 10
            };
            var impares = new List <int> {
                1, 3, 5, 7, 9
            };
            var primos = new List <int> {
                1, 2, 3, 5, 7
            };

            ISet <int> zeroAdez = new HashSet <int>();

            pares.ForEach(n => zeroAdez.Add(n));
            impares.ForEach(n => zeroAdez.Add(n));
            primos.ForEach(n => zeroAdez.Add(n));

            foreach (var n in zeroAdez)
            {
                Console.WriteLine(n);
            }
            Console.WriteLine();

            //TAREFA 7: ASSOCIANDO CHAVES E VALORES

            Dictionary <string, string> weekDays = new Dictionary <string, string>
            {
                { "SEG", "Monday" },
                { "TER", "Tuesday" },
                { "QUA", "Wednesday" },
                { "QUI", "Thursday" },
                { "SEX", "Friday" }
            };

            weekDays.Add("SAB", "Saturday");
            weekDays.Add("DOM", "Sunday");

            foreach (var chaveValor in weekDays)
            {
                Console.WriteLine("{0} - {1}", chaveValor.Key, chaveValor.Value);
            }

            Console.ReadLine();
        }
예제 #54
0
파일: Program.cs 프로젝트: mjsmith11/AOC
        static long part2(string input)
        {
            LinkedList <int> cups = new LinkedList <int>();
            Dictionary <int, LinkedListNode <int> > lookup = new Dictionary <int, LinkedListNode <int> >();

            for (int i = 0; i < input.Length; i++)
            {
                cups.AddLast(int.Parse(input.Substring(i, 1)));
                lookup[int.Parse(input.Substring(i, 1))] = cups.Last;
            }
            for (int i = 10; i <= 1000000; i++)
            {
                cups.AddLast(i);
                lookup[i] = cups.Last;
            }
            LinkedListNode <int> current = cups.First;

            for (int i = 0; i < 10000000; i++)
            {
                int currentLabel = current.Value;

                LinkedListNode <int> cupNode1 = getNextNode(cups, current);
                LinkedListNode <int> cupNode2 = getNextNode(cups, cupNode1);
                LinkedListNode <int> cupNode3 = getNextNode(cups, cupNode2);

                int myCup1 = cupNode1.Value;
                cups.Remove(cupNode1);

                int myCup2 = cupNode2.Value;
                cups.Remove(cupNode2);

                int myCup3 = cupNode3.Value;
                cups.Remove(cupNode3);

                // pick destination
                int desiredLabel = currentLabel - 1;
                if (desiredLabel < 1)
                {
                    desiredLabel += 1000000;
                }
                while (myCup1 == desiredLabel || myCup2 == desiredLabel || myCup3 == desiredLabel)
                {
                    desiredLabel--;
                    if (desiredLabel < 1)
                    {
                        desiredLabel += 1000000;
                    }
                }
                LinkedListNode <int> destination = lookup[desiredLabel];

                cups.AddAfter(destination, cupNode1);
                cups.AddAfter(cupNode1, cupNode2);
                cups.AddAfter(cupNode2, cupNode3);

                //pick the new current
                current = getNextNode(cups, current);
            }

            //find 1
            LinkedListNode <int> one   = cups.Find(1);
            LinkedListNode <int> next1 = one.Next;
            LinkedListNode <int> next2 = next1.Next;

            return((long)next1.Value * (long)next2.Value);
        }
예제 #55
0
        protected List <int> PlayGameLinkedList(List <int> cups, int iterations)
        {
            var list          = new LinkedList <int>(cups);
            var cupDictionary = new LinkedListNode <int> [list.Count];

            var cupNode = list.First;

            while (cupNode != null)
            {
                cupDictionary[cupNode.Value - 1] = cupNode;
                cupNode = cupNode.Next;
            }

            var minCup = cups.Min();
            var maxCup = cups.Max();

            LinkedListNode <int> currentItem = list.First;

            var removedItems = new LinkedListNode <int> [3];

            for (var i = 0; i < iterations; i++)
            {
                for (var j = 0; j < 3; j++)
                {
                    if (currentItem.Next != null)
                    {
                        removedItems[j] = currentItem.Next;
                        list.Remove(currentItem.Next);
                    }
                    else
                    {
                        removedItems[j] = list.First;
                        list.Remove(list.First);
                    }
                }

                var requiredValue = currentItem.Value - 1;

                if (requiredValue < minCup)
                {
                    requiredValue = maxCup;
                }

                while (removedItems.Any(a => a.Value == requiredValue))
                {
                    requiredValue--;
                    if (requiredValue < minCup)
                    {
                        requiredValue = maxCup;
                    }
                }

                var insertNode = cupDictionary[requiredValue - 1];

                foreach (var value in removedItems)
                {
                    list.AddAfter(insertNode, value);
                    insertNode = value;
                }

                currentItem = currentItem.Next;

                if (currentItem == null)
                {
                    currentItem = list.First;
                }
            }

            return(list.ToList());
        }
예제 #56
0
파일: Series.cs 프로젝트: rioka/nfx
        /// <summary>
        /// Adds sample to the series at the appropriate position.
        /// This method respects MaxSamples and first deletes older samples making room for new additions
        /// </summary>
        protected void Add(ITimeSeriesSample sample)
        {
            if (sample == null)
            {
                throw new WFormsException(StringConsts.ARGUMENT_ERROR + "TimeSeries.Add(sample==null)");
            }

            //remove data over max samples
            while (m_Data.Count >= m_MaxSamples)
            {
                m_Data.RemoveFirst();
            }


            var dt   = sample.TimeStamp;
            var head = m_Data.First;

            if (head == null || head.Value.TimeStamp >= dt)
            {
                m_Data.AddFirst(sample);
                return;
            }

            var last = m_Data.Last;

            if (last.Value.TimeStamp <= dt)
            {
                m_Data.AddLast(sample);
                return;
            }


            var d1 = dt - head.Value.TimeStamp;
            var d2 = last.Value.TimeStamp - dt;

            if (d1 < d2)
            {
                var node = head;
                while (node != null)
                {
                    if (node.Value.TimeStamp >= dt)
                    {
                        m_Data.AddBefore(node, sample);
                        return;
                    }
                    node = node.Next;
                }
                m_Data.AddLast(sample);
            }
            else
            {
                var node = last;
                while (node != null)
                {
                    if (node.Value.TimeStamp <= dt)
                    {
                        m_Data.AddAfter(node, sample);
                        return;
                    }
                    node = node.Previous;
                }
                m_Data.AddFirst(sample);
            }
        }
예제 #57
0
        static void Main(string[] args)
        {
            LinkedList <string> l = new LinkedList <string>();

            l.AddLast("One");
            l.AddLast("Two");
            l.AddLast("Three");

            foreach (var element in l)
            {
                Console.WriteLine(element);
            }
            Console.WriteLine();

            // Example 2 - A linked-list is a collection type that on the surface is very similar to the List<T> type,
            // but the big difference is how the data is stored internally

            LinkedList <string> months = new LinkedList <string>();

            months.AddLast("March");
            months.AddFirst("January");

            var march = months.Find("March");

            months.AddBefore(march, "February");
            months.AddAfter(march, "April");

            foreach (var month in months)
            {
                Console.WriteLine(month);
            }
            Console.WriteLine();

            // Example 3 - illustrate the LinkedList<T> class properties

            // Created LinkedList of string
            LinkedList <string> myList = new LinkedList <string>();

            // Adding Nodes in the LinkedList
            myList.AddLast("GeeksforGeeks");
            myList.AddLast("GFG");
            myList.AddLast("Data structures");
            myList.AddLast("Noida");

            // Count Property
            // To get the first Node of the LinkedList
            if (myList.Count > 0)
            {
                Console.WriteLine(myList.First.Value);
            }
            else
            {
                Console.WriteLine("LinkedList is Empty");
            }

            // Last Property
            // To get the last Node of the LinkedList
            if (myList.Count > 0)
            {
                Console.WriteLine(myList.Last.Value);
            }
            else
            {
                Console.WriteLine("LinkedList is Empty");
            }
            Console.WriteLine();
        }
예제 #58
0
        // Summary:
        //     Sorts the elements in the entire System.Collections.Generic.LinkedList<T> using
        //     the specified System.Comparison<T>.
        //
        // Parameters:
        //   comparison:
        //     The System.Comparison<T> to use when comparing elements.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     comparison is null.
        public static void Sort <T>(this LinkedList <T> @this, Comparison <T> comparison)
        {
            if (@this == null)
            {
                throw new NullReferenceException();
            }

            if (comparison == null)
            {
                throw new ArgumentNullException("comparison");
            }

            int count = @this.Count;

            if (count <= 1)
            {
                return;
            }

            // merge pairs of lists of doubling size
            for (int mergeLength = 1; mergeLength < count; mergeLength *= 2)
            {
                LinkedListNode <T> mergedTail = null;
                LinkedListNode <T> head2;
                for (LinkedListNode <T> head1 = @this.First; head1 != null; head1 = head2)
                {
                    // skip over the 1st part to the start 2nd
                    head2 = head1;
                    int length1;
                    for (length1 = 0; length1 < mergeLength && head2 != null; ++length1)
                    {
                        head2 = head2.Next;
                    }

                    // assume we have a full-length 2nd part
                    int length2 = mergeLength;

                    // while we still have items to merge
                    while (length1 > 0 || (length2 > 0 && head2 != null))
                    {
                        LinkedListNode <T> next;

                        // determine which part the next item comes from
                        if (length1 != 0 && !(length2 != 0 && head2 != null && comparison(head1.Value, head2.Value) > 0))
                        {
                            // take item from 1st part
                            Debug.Assert(head1 != null);
                            next  = head1;
                            head1 = head1.Next;

                            Debug.Assert(length1 > 0);
                            --length1;
                        }
                        else
                        {
                            // take item from 2nd part
                            Debug.Assert(head2 != null);
                            next  = head2;
                            head2 = head2.Next;

                            Debug.Assert(length2 > 0);
                            --length2;
                        }

                        // append the next item to the merged list
                        if (mergedTail == null)
                        {
                            // start a new merged list at the front of the source list
                            if (@this.First != next)    // check for no-op
                            {
                                @this.Remove(next);
                                @this.AddFirst(next);
                            }
                        }
                        else if (mergedTail.Next != next)   // check for no-op
                        {
                            @this.Remove(next);
                            @this.AddAfter(mergedTail, next);
                        }

                        // advance the merged tail
                        mergedTail = next;
                    }
                }
            }
        }
예제 #59
0
        static void Test2()
        {
            LinkedList <int>     list1 = new LinkedList <int>();
            LinkedListNode <int> node;

            node = list1.AddLast(10);
            //list1.AddFirst(5);
            node = list1.AddFirst(5);
            list1.Print("list1", "\t");
            //5 10
            list1.AddAfter(node, 20);
            list1.Print("list1", "\t");

            LinkedListNode <int> node2 = new LinkedListNode <int>(50);

            list1.AddAfter(node, node2);
            list1.Print("list1", "\t");
            Console.WriteLine(node.Next.Next.Value);
            Console.WriteLine(node2.Next.Next.Value);

            LinkedListNode <int> node3 = node2.Next;

            Console.WriteLine(node3.Value);
            Console.WriteLine(node3.Previous.Previous.Value);


            Student stud = new Student {
                Name = "Anna", Bday = new DateTime(1986, 5, 12)
            };
            List <Student> group = new List <Student> {
                null,
                new Student {
                    Name = "Mark", Bday = new DateTime(1996, 12, 13)
                },
                new Student {
                    Name = "Ivan", Bday = new DateTime(2013, 10, 25)
                },
                stud,
                new Student {
                    Name = "Oleg", Bday = new DateTime(2015, 1, 16)
                }
            };
            LinkedList <Student> listst = new LinkedList <Student>(group);

            listst.Print("listst");
            //var nodefind=listst.Find(new Student { Name = "Anna", Bday = new DateTime(1986, 5, 12) });
            // var nodefind=listst.Find(stud);
            var nodefind = listst.Find(new Student {
                Name = "Ivan", Bday = new DateTime(2013, 10, 25)
            });

            if (nodefind is null)
            {
                Console.WriteLine("HEMA");
            }
            else
            {
                Console.WriteLine($"E {nodefind.Value}");
            }

            var col = listst.OrderBy(x => x).ToList();
            LinkedList <Student> listsort = new LinkedList <Student>(col);

            listsort.Print("listst");
            //foreach (var item in col)
            //{
            //    Console.WriteLine(item);
            //}
            IEnumerable <Student> col2 = listst.OrderBy(x => x, new CompDate());
            //ToList();
            LinkedList <Student> listsort2 = new LinkedList <Student>(col2);

            listsort2.Print("listst2");
        }
        public void AddBefore_LLNode_LLNode()
        {
            LinkedList <T> linkedList = new LinkedList <T>();
            int            arraySize  = 16;
            int            seed       = 8293;

            T[] tempItems, headItems, headItemsReverse, tailItems, tailItemsReverse;

            headItems        = new T[arraySize];
            tailItems        = new T[arraySize];
            headItemsReverse = new T[arraySize];
            tailItemsReverse = new T[arraySize];
            for (int i = 0; i < arraySize; i++)
            {
                int index = (arraySize - 1) - i;
                T   head  = CreateT(seed++);
                T   tail  = CreateT(seed++);
                headItems[i]            = head;
                headItemsReverse[index] = head;
                tailItems[i]            = tail;
                tailItemsReverse[index] = tail;
            }

            //[] Verify value is default(T)
            linkedList = new LinkedList <T>();
            linkedList.AddFirst(headItems[0]);
            linkedList.AddBefore(linkedList.First, new LinkedListNode <T>(default(T)));
            InitialItems_Tests(linkedList, new T[] { default(T), headItems[0] });

            //[] Node is the Head
            linkedList = new LinkedList <T>();
            linkedList.AddFirst(headItems[0]);
            for (int i = 1; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.First, new LinkedListNode <T>(headItems[i]));
            }

            InitialItems_Tests(linkedList, headItemsReverse);

            //[] Node is the Tail
            linkedList = new LinkedList <T>();
            linkedList.AddFirst(headItems[0]);
            tempItems = new T[headItems.Length];
            Array.Copy(headItems, 1, tempItems, 0, headItems.Length - 1);
            tempItems[tempItems.Length - 1] = headItems[0];
            for (int i = 1; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.Last, new LinkedListNode <T>(headItems[i]));
            }

            InitialItems_Tests(linkedList, tempItems);

            //[] Node is after the Head
            linkedList = new LinkedList <T>();
            linkedList.AddFirst(headItems[0]);
            linkedList.AddLast(headItems[1]);
            tempItems = new T[headItems.Length];
            Array.Copy(headItems, 0, tempItems, 0, headItems.Length);
            Array.Reverse(tempItems, 1, headItems.Length - 1);

            for (int i = 2; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.First.Next, new LinkedListNode <T>(headItems[i]));
            }

            InitialItems_Tests(linkedList, tempItems);

            //[] Node is before the Tail
            linkedList = new LinkedList <T>();
            linkedList.AddFirst(headItems[0]);
            linkedList.AddLast(headItems[1]);

            tempItems = new T[headItems.Length];
            Array.Copy(headItems, 2, tempItems, 0, headItems.Length - 2);
            tempItems[tempItems.Length - 2] = headItems[0];
            tempItems[tempItems.Length - 1] = headItems[1];

            for (int i = 2; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.Last.Previous, new LinkedListNode <T>(headItems[i]));
            }

            InitialItems_Tests(linkedList, tempItems);

            //[] Node is somewhere in the middle
            linkedList = new LinkedList <T>();
            linkedList.AddFirst(headItems[0]);
            linkedList.AddLast(headItems[1]);
            linkedList.AddLast(headItems[2]);

            tempItems = new T[headItems.Length];
            Array.Copy(headItems, 3, tempItems, 0, headItems.Length - 3);
            tempItems[tempItems.Length - 3] = headItems[0];
            tempItems[tempItems.Length - 2] = headItems[1];
            tempItems[tempItems.Length - 1] = headItems[2];

            for (int i = 3; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.Last.Previous.Previous, new LinkedListNode <T>(headItems[i]));
            }

            InitialItems_Tests(linkedList, tempItems);

            //[] Call AddBefore several times remove some of the items
            linkedList = new LinkedList <T>();
            linkedList.AddFirst(headItems[0]);
            for (int i = 1; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.First, new LinkedListNode <T>(headItems[i]));
            }

            linkedList.Remove(headItems[2]);
            linkedList.Remove(headItems[headItems.Length - 3]);
            linkedList.Remove(headItems[1]);
            linkedList.Remove(headItems[headItems.Length - 2]);
            linkedList.RemoveFirst();
            linkedList.RemoveLast();
            //With the above remove we should have removed the first and last 3 items
            tempItems = new T[headItemsReverse.Length - 6];
            Array.Copy(headItemsReverse, 3, tempItems, 0, headItemsReverse.Length - 6);

            InitialItems_Tests(linkedList, tempItems);

            for (int i = 0; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.First, new LinkedListNode <T>(tailItems[i]));
            }

            T[] tempItems2 = new T[tailItemsReverse.Length + tempItems.Length];
            Array.Copy(tailItemsReverse, 0, tempItems2, 0, tailItemsReverse.Length);
            Array.Copy(tempItems, 0, tempItems2, tailItemsReverse.Length, tempItems.Length);

            InitialItems_Tests(linkedList, tempItems2);

            //[] Call AddBefore several times remove all of the items
            linkedList = new LinkedList <T>();
            linkedList.AddFirst(headItems[0]);
            for (int i = 1; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.First, new LinkedListNode <T>(headItems[i]));
            }

            for (int i = 0; i < arraySize; ++i)
            {
                linkedList.RemoveFirst();
            }

            linkedList.AddFirst(tailItems[0]);
            for (int i = 1; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.First, new LinkedListNode <T>(tailItems[i]));
            }

            InitialItems_Tests(linkedList, tailItemsReverse);

            //[] Call AddBefore several times then call Clear
            linkedList = new LinkedList <T>();
            linkedList.AddFirst(headItems[0]);
            for (int i = 1; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.First, new LinkedListNode <T>(headItems[i]));
            }

            linkedList.Clear();

            linkedList.AddFirst(tailItems[0]);
            for (int i = 1; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.First, new LinkedListNode <T>(tailItems[i]));
            }

            InitialItems_Tests(linkedList, tailItemsReverse);

            //[] Mix AddBefore and AddAfter calls
            linkedList = new LinkedList <T>();
            linkedList.AddLast(headItems[0]);
            linkedList.AddLast(tailItems[0]);
            for (int i = 1; i < arraySize; ++i)
            {
                linkedList.AddBefore(linkedList.First, new LinkedListNode <T>(headItems[i]));
                linkedList.AddAfter(linkedList.Last, new LinkedListNode <T>(tailItems[i]));
            }

            tempItems = new T[headItemsReverse.Length + tailItems.Length];
            Array.Copy(headItemsReverse, 0, tempItems, 0, headItemsReverse.Length);
            Array.Copy(tailItems, 0, tempItems, headItemsReverse.Length, tailItems.Length);

            InitialItems_Tests(linkedList, tempItems);
        }