/// <summary> /// Converts the given end node and path node information /// to a path from the start node to the end node /// </summary> /// <param name="path">path to convert</param> /// <returns>string for path</returns> private string ConvertPathToString(GraphNode <int> endNode, Dictionary <GraphNode <int>, PathNodeInfo <int> > pathNodes) { //Build linked list for path in correct order System.Collections.Generic.LinkedList <GraphNode <int> > path = new System.Collections.Generic.LinkedList <GraphNode <int> >(); path.AddFirst(endNode); GraphNode <int> previous = pathNodes[endNode].Previous; while (previous != null) { path.AddFirst(previous); previous = pathNodes[previous].Previous; } //Build and return string StringBuilder pathString = new StringBuilder(); System.Collections.Generic.LinkedListNode <GraphNode <int> > currentNode = path.First; int nodeCount = 0; while (currentNode != null) { nodeCount++; pathString.Append(currentNode.Value.Value); if (nodeCount < path.Count) { pathString.Append(" "); } currentNode = currentNode.Next; } return(pathString.ToString()); }
public int Get(int key) { if (_values.ContainsKey(key)) { LinkedListNode <int> node = _values[key]; int value = node.Value; _linkedList.Remove(node); var updated = _linkedList.AddFirst(value); _values[key] = updated; return(value); } return(-1); }
/// <summary> /// O(log(n)) /// </summary> /// <param name="key"></param> /// <returns></returns> public TValue this[TKey key] { get { LinkedListNode <KeyValuePair <TKey, TValue> > llNode = sortedList[key]; //O(log(n)) linkedList.Remove(llNode); //O(1) linkedList.AddFirst(llNode); //O(1) return(llNode.Value.Value); } set { LinkedListNode <KeyValuePair <TKey, TValue> > llNode = sortedList[key]; //O(log(n)) linkedList.Remove(llNode); //O(1) linkedList.AddFirst(llNode); //O(1) llNode.Value = new KeyValuePair <TKey, TValue>(key, value); //llNode.Value.Value=value; } }
public static Board BuildNewBoard() { var blockLists = new System.Collections.Generic.List<System.Collections.Generic.LinkedList<Block>>(); for (int counter = 0; counter < maxNumberOfLists; counter++) { var linkedList = new System.Collections.Generic.LinkedList<Block>(); int numberOfBlocksInTheList = randomNumberGenerator.Next(3, 6); for (int listCounter = 0; listCounter < numberOfBlocksInTheList; listCounter++) { var block = GetNewRandomBlock(); linkedList.AddFirst(block); } for (int listCounter = numberOfBlocksInTheList; listCounter < 9; listCounter++) { var block = new Block(); linkedList.AddLast(block); } blockLists.Add(linkedList); } Board board = new Board() { BlockLists = blockLists, inDanger = false, active = true }; return board; }
public static Board BuildNewBoard() { int numberOfBlocksInTheList = 3; var blockLists = new System.Collections.Generic.List<System.Collections.Generic.LinkedList<Block>>(); for (int counter = 0; counter < maxNumberOfLists; counter++) { var linkedList = new System.Collections.Generic.LinkedList<Block>(); for (int listCounter = 0; listCounter < numberOfBlocksInTheList; listCounter++) { var block = GetNewRandomBlock(); linkedList.AddFirst(block); } blockLists.Add(linkedList); } Board board = new Board() { BlockLists = blockLists }; return board; }
private void AddFrontButton_Click(object sender, EventArgs e) { if (ItemTextBox.Text != "") { todoList.AddFirst(ItemTextBox.Text); } DisplayList(); }
/// <inheritdoc/> public bool TryGetValue(K key, bool moveToTop, out V value) { LinkedListNode <Pair <K, V> > valueContainer; if (map.TryGetValue(key, out valueContainer)) { if (moveToTop) { list.Remove(valueContainer); list.AddFirst(valueContainer); } value = valueContainer.Value.Second; return(true); } value = default(V); return(false); }
public void GedraagtMijnLinkedListZichNetZoAlsDieVanDotNet() { var ours = new LinkedList <int> { 1, 2, 3, 4 }; var theirs = new System.Collections.Generic.LinkedList <int>(); theirs.AddAfter(theirs.AddAfter(theirs.AddAfter(theirs.AddFirst(1), 2), 3), 4); Assert.Equal(theirs, ours); }
public int Get(int key) { if (_hash.ContainsKey(key)) { LinkedListNode <CacheData> node = _hash[key]; if (node == _linkedList.First) { return(node.Value.Value); } _linkedList.Remove(node); // add as new head CacheData data = new CacheData(node.Value.Key, node.Value.Value); _linkedList.AddFirst(new LinkedListNode <CacheData>(data)); _hash[key] = _linkedList.First; return(node.Value.Value); } return(-1); }
static void Main() { var linked = new System.Collections.Generic.LinkedList <int>(); var node = new LinkedListNode <int>(1); linked.AddFirst(node); var x = linked.AddAfter(node, 5); var list = new LinkedList <int>() { 1, 2, 3, 4 }; list.Print(); list.Print(); list.FindFirst(4); Console.Read(); }
private System.Collections.Generic.LinkedList <State> GetSucc(State u) { var s = new System.Collections.Generic.LinkedList <State>(); State tempState; if (Occupied(u)) { return(s); } // Generate the successors, starting at the immediate right, // Moving in a clockwise manner tempState = new State(u.X + 1, u.Y, new Pair <double, double>(-1, -1)); s.AddFirst(tempState); if (allowDiagonalPathing) { tempState = new State(u.X + 1, u.Y + 1, new Pair <double, double>(-1, -1)); s.AddFirst(tempState); } tempState = new State(u.X, u.Y + 1, new Pair <double, double>(-1, -1)); s.AddFirst(tempState); if (allowDiagonalPathing) { tempState = new State(u.X - 1, u.Y + 1, new Pair <double, double>(-1, -1)); s.AddFirst(tempState); } tempState = new State(u.X - 1, u.Y, new Pair <double, double>(-1, -1)); s.AddFirst(tempState); if (allowDiagonalPathing) { tempState = new State(u.X - 1, u.Y - 1, new Pair <double, double>(-1, -1)); s.AddFirst(tempState); } tempState = new State(u.X, u.Y - 1, new Pair <double, double>(-1, -1)); s.AddFirst(tempState); if (allowDiagonalPathing) { tempState = new State(u.X + 1, u.Y - 1, new Pair <double, double>(-1, -1)); s.AddFirst(tempState); } return(s); }
public void Add(int n, T t) { if (n == 0) { if (Node != null) { Node.Value = t; } return; } Enumerator itr = new Enumerator(this); if (!itr.Move(n - Math.Sign(n))) { if (begin) { List.AddFirst(t); } else { List.AddLast(t); } /*if (!itr.Move(-Math.Sign(n))) * { * itr.Move(Math.Sign(n)); * n *= -1; * }*/ } else { if (n > 0) { List.AddAfter(itr.Node, t); } else if (n < 0) { List.AddBefore(itr.Node, t); } } }
public void Add(TKey key, TValue value) { if (m_items == null) { m_items = new System.Collections.Generic.LinkedList <HashTableNodePair <TKey, TValue> >(); } else { // this is for collision management foreach (HashTableNodePair <TKey, TValue> pair in m_items) { if (pair.Key.Equals(key)) { throw new ArgumentException("key is already present in the hashtable"); } } } m_items.AddFirst(new HashTableNodePair <TKey, TValue>(key, value)); }
// Adds the specified item to the stack public void Push(T item) { _list.AddFirst(item); }
public void Populate() { #region Types of Keywords FieldPublicDynamic = new { PropPublic1 = "A", PropPublic2 = 1, PropPublic3 = "B", PropPublic4 = "B", PropPublic5 = "B", PropPublic6 = "B", PropPublic7 = "B", PropPublic8 = "B", PropPublic9 = "B", PropPublic10 = "B", PropPublic11 = "B", PropPublic12 = new { PropSubPublic1 = 0, PropSubPublic2 = 1, PropSubPublic3 = 2 } }; FieldPublicObject = new StringBuilder("Object - StringBuilder"); FieldPublicInt32 = int.MaxValue; FieldPublicInt64 = long.MaxValue; FieldPublicULong = ulong.MaxValue; FieldPublicUInt = uint.MaxValue; FieldPublicDecimal = 100000.999999m; FieldPublicDouble = 100000.999999d; FieldPublicChar = 'A'; FieldPublicByte = byte.MaxValue; FieldPublicBoolean = true; FieldPublicSByte = sbyte.MaxValue; FieldPublicShort = short.MaxValue; FieldPublicUShort = ushort.MaxValue; FieldPublicFloat = 100000.675555f; FieldPublicInt32Nullable = int.MaxValue; FieldPublicInt64Nullable = 2; FieldPublicULongNullable = ulong.MaxValue; FieldPublicUIntNullable = uint.MaxValue; FieldPublicDecimalNullable = 100000.999999m; FieldPublicDoubleNullable = 100000.999999d; FieldPublicCharNullable = 'A'; FieldPublicByteNullable = byte.MaxValue; FieldPublicBooleanNullable = true; FieldPublicSByteNullable = sbyte.MaxValue; FieldPublicShortNullable = short.MaxValue; FieldPublicUShortNullable = ushort.MaxValue; FieldPublicFloatNullable = 100000.675555f; #endregion #region System FieldPublicDateTime = new DateTime(2000, 1, 1, 1, 1, 1); FieldPublicTimeSpan = new TimeSpan(1, 10, 40); FieldPublicEnumDateTimeKind = DateTimeKind.Local; // Instantiate date and time using Persian calendar with years, // months, days, hours, minutes, seconds, and milliseconds FieldPublicDateTimeOffset = new DateTimeOffset(1387, 2, 12, 8, 6, 32, 545, new System.Globalization.PersianCalendar(), new TimeSpan(1, 0, 0)); FieldPublicIntPtr = new IntPtr(100); FieldPublicTimeZone = TimeZone.CurrentTimeZone; FieldPublicTimeZoneInfo = TimeZoneInfo.Utc; FieldPublicTuple = Tuple.Create <string, int, decimal>("T-string\"", 1, 1.1m); FieldPublicType = typeof(object); FieldPublicUIntPtr = new UIntPtr(100); FieldPublicUri = new Uri("http://www.site.com"); FieldPublicVersion = new Version(1, 0, 100, 1); FieldPublicGuid = new Guid("d5010f5b-0cd1-44ca-aacb-5678b9947e6c"); FieldPublicSingle = Single.MaxValue; FieldPublicException = new Exception("Test error", new Exception("inner exception")); FieldPublicEnumNonGeneric = EnumTest.ValueA; FieldPublicAction = () => true.Equals(true); FieldPublicAction2 = (a, b) => true.Equals(true); FieldPublicFunc = () => true; FieldPublicFunc2 = (a, b) => true; #endregion #region Arrays and Collections FieldPublicArrayUni = new string[2]; FieldPublicArrayUni[0] = "[0]"; FieldPublicArrayUni[1] = "[1]"; FieldPublicArrayTwo = new string[2, 2]; FieldPublicArrayTwo[0, 0] = "[0, 0]"; FieldPublicArrayTwo[0, 1] = "[0, 1]"; FieldPublicArrayTwo[1, 0] = "[1, 0]"; FieldPublicArrayTwo[1, 1] = "[1, 1]"; FieldPublicArrayThree = new string[1, 1, 2]; FieldPublicArrayThree[0, 0, 0] = "[0, 0, 0]"; FieldPublicArrayThree[0, 0, 1] = "[0, 0, 1]"; FieldPublicJaggedArrayTwo = new string[2][]; FieldPublicJaggedArrayTwo[0] = new string[5] { "a", "b", "c", "d", "e" }; FieldPublicJaggedArrayTwo[1] = new string[4] { "a1", "b1", "c1", "d1" }; FieldPublicJaggedArrayThree = new string[1][][]; FieldPublicJaggedArrayThree[0] = new string[1][]; FieldPublicJaggedArrayThree[0][0] = new string[2]; FieldPublicJaggedArrayThree[0][0][0] = "[0][0][0]"; FieldPublicJaggedArrayThree[0][0][1] = "[0][0][1]"; FieldPublicMixedArrayAndJagged = new int[3][, ] { new int[, ] { { 1, 3 }, { 5, 7 } }, new int[, ] { { 0, 2 }, { 4, 6 }, { 8, 10 } }, new int[, ] { { 11, 22 }, { 99, 88 }, { 0, 9 } } }; FieldPublicDictionary = new System.Collections.Generic.Dictionary <string, string>(); FieldPublicDictionary.Add("Key1", "Value1"); FieldPublicDictionary.Add("Key2", "Value2"); FieldPublicDictionary.Add("Key3", "Value3"); FieldPublicDictionary.Add("Key4", "Value4"); FieldPublicList = new System.Collections.Generic.List <int>(); FieldPublicList.Add(0); FieldPublicList.Add(1); FieldPublicList.Add(2); FieldPublicQueue = new System.Collections.Generic.Queue <int>(); FieldPublicQueue.Enqueue(10); FieldPublicQueue.Enqueue(11); FieldPublicQueue.Enqueue(12); FieldPublicHashSet = new System.Collections.Generic.HashSet <string>(); FieldPublicHashSet.Add("HashSet1"); FieldPublicHashSet.Add("HashSet2"); FieldPublicSortedSet = new System.Collections.Generic.SortedSet <string>(); FieldPublicSortedSet.Add("SortedSet1"); FieldPublicSortedSet.Add("SortedSet2"); FieldPublicSortedSet.Add("SortedSet3"); FieldPublicStack = new System.Collections.Generic.Stack <string>(); FieldPublicStack.Push("Stack1"); FieldPublicStack.Push("Stack2"); FieldPublicStack.Push("Stack3"); FieldPublicLinkedList = new System.Collections.Generic.LinkedList <string>(); FieldPublicLinkedList.AddFirst("LinkedList1"); FieldPublicLinkedList.AddLast("LinkedList2"); FieldPublicLinkedList.AddAfter(FieldPublicLinkedList.Find("LinkedList1"), "LinkedList1.1"); FieldPublicObservableCollection = new System.Collections.ObjectModel.ObservableCollection <string>(); FieldPublicObservableCollection.Add("ObservableCollection1"); FieldPublicObservableCollection.Add("ObservableCollection2"); FieldPublicKeyedCollection = new MyDataKeyedCollection(); FieldPublicKeyedCollection.Add(new MyData() { Data = "data1", Id = 0 }); FieldPublicKeyedCollection.Add(new MyData() { Data = "data2", Id = 1 }); var list = new List <string>(); list.Add("list1"); list.Add("list2"); list.Add("list3"); FieldPublicReadOnlyCollection = new ReadOnlyCollection <string>(list); FieldPublicReadOnlyDictionary = new ReadOnlyDictionary <string, string>(FieldPublicDictionary); FieldPublicReadOnlyObservableCollection = new ReadOnlyObservableCollection <string>(FieldPublicObservableCollection); FieldPublicCollection = new Collection <string>(); FieldPublicCollection.Add("collection1"); FieldPublicCollection.Add("collection2"); FieldPublicCollection.Add("collection3"); FieldPublicArrayListNonGeneric = new System.Collections.ArrayList(); FieldPublicArrayListNonGeneric.Add(1); FieldPublicArrayListNonGeneric.Add("a"); FieldPublicArrayListNonGeneric.Add(10.0m); FieldPublicArrayListNonGeneric.Add(new DateTime(2000, 01, 01)); FieldPublicBitArray = new System.Collections.BitArray(3); FieldPublicBitArray[2] = true; FieldPublicSortedList = new System.Collections.SortedList(); FieldPublicSortedList.Add("key1", 1); FieldPublicSortedList.Add("key2", 2); FieldPublicSortedList.Add("key3", 3); FieldPublicSortedList.Add("key4", 4); FieldPublicHashtableNonGeneric = new System.Collections.Hashtable(); FieldPublicHashtableNonGeneric.Add("key1", 1); FieldPublicHashtableNonGeneric.Add("key2", 2); FieldPublicHashtableNonGeneric.Add("key3", 3); FieldPublicHashtableNonGeneric.Add("key4", 4); FieldPublicQueueNonGeneric = new System.Collections.Queue(); FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric1"); FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric2"); FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric3"); FieldPublicStackNonGeneric = new System.Collections.Stack(); FieldPublicStackNonGeneric.Push("StackNonGeneric1"); FieldPublicStackNonGeneric.Push("StackNonGeneric2"); FieldPublicIEnumerable = FieldPublicSortedList; FieldPublicBlockingCollection = new System.Collections.Concurrent.BlockingCollection <string>(); FieldPublicBlockingCollection.Add("BlockingCollection1"); FieldPublicBlockingCollection.Add("BlockingCollection2"); FieldPublicConcurrentBag = new System.Collections.Concurrent.ConcurrentBag <string>(); FieldPublicConcurrentBag.Add("ConcurrentBag1"); FieldPublicConcurrentBag.Add("ConcurrentBag2"); FieldPublicConcurrentBag.Add("ConcurrentBag3"); FieldPublicConcurrentDictionary = new System.Collections.Concurrent.ConcurrentDictionary <string, int>(); FieldPublicConcurrentDictionary.GetOrAdd("ConcurrentDictionary1", 0); FieldPublicConcurrentDictionary.GetOrAdd("ConcurrentDictionary2", 0); FieldPublicConcurrentQueue = new System.Collections.Concurrent.ConcurrentQueue <string>(); FieldPublicConcurrentQueue.Enqueue("ConcurrentQueue1"); FieldPublicConcurrentQueue.Enqueue("ConcurrentQueue2"); FieldPublicConcurrentStack = new System.Collections.Concurrent.ConcurrentStack <string>(); FieldPublicConcurrentStack.Push("ConcurrentStack1"); FieldPublicConcurrentStack.Push("ConcurrentStack2"); // FieldPublicOrderablePartitioner = new OrderablePartitioner(); // FieldPublicPartitioner; // FieldPublicPartitionerNonGeneric; FieldPublicHybridDictionary = new System.Collections.Specialized.HybridDictionary(); FieldPublicHybridDictionary.Add("HybridDictionaryKey1", "HybridDictionary1"); FieldPublicHybridDictionary.Add("HybridDictionaryKey2", "HybridDictionary2"); FieldPublicListDictionary = new System.Collections.Specialized.ListDictionary(); FieldPublicListDictionary.Add("ListDictionaryKey1", "ListDictionary1"); FieldPublicListDictionary.Add("ListDictionaryKey2", "ListDictionary2"); FieldPublicNameValueCollection = new System.Collections.Specialized.NameValueCollection(); FieldPublicNameValueCollection.Add("Key1", "Value1"); FieldPublicNameValueCollection.Add("Key2", "Value2"); FieldPublicOrderedDictionary = new System.Collections.Specialized.OrderedDictionary(); FieldPublicOrderedDictionary.Add(1, "OrderedDictionary1"); FieldPublicOrderedDictionary.Add(2, "OrderedDictionary1"); FieldPublicOrderedDictionary.Add("OrderedDictionaryKey2", "OrderedDictionary2"); FieldPublicStringCollection = new System.Collections.Specialized.StringCollection(); FieldPublicStringCollection.Add("StringCollection1"); FieldPublicStringCollection.Add("StringCollection2"); #endregion #region Several PropXmlDocument = new XmlDocument(); PropXmlDocument.LoadXml("<xml>something</xml>"); var tr = new StringReader("<Root>Content</Root>"); PropXDocument = XDocument.Load(tr); PropStream = GenerateStreamFromString("Stream"); PropBigInteger = new System.Numerics.BigInteger(100); PropStringBuilder = new StringBuilder("StringBuilder"); FieldPublicIQueryable = new List <string>() { "IQueryable" }.AsQueryable(); #endregion #region Custom FieldPublicMyCollectionPublicGetEnumerator = new MyCollectionPublicGetEnumerator("a b c", new char[] { ' ' }); FieldPublicMyCollectionInheritsPublicGetEnumerator = new MyCollectionInheritsPublicGetEnumerator("a b c", new char[] { ' ' }); FieldPublicMyCollectionExplicitGetEnumerator = new MyCollectionExplicitGetEnumerator("a b c", new char[] { ' ' }); FieldPublicMyCollectionInheritsExplicitGetEnumerator = new MyCollectionInheritsExplicitGetEnumerator("a b c", new char[] { ' ' }); FieldPublicMyCollectionInheritsTooIEnumerable = new MyCollectionInheritsTooIEnumerable("a b c", new char[] { ' ' }); FieldPublicEnumSpecific = EnumTest.ValueB; MyDelegate = MethodDelegate; EmptyClass = new EmptyClass(); StructGeneric = new ThreeTuple <int>(0, 1, 2); StructGenericNullable = new ThreeTuple <int>(0, 1, 2); FieldPublicNullable = new Nullable <ThreeTuple <int> >(StructGeneric); #endregion }
public LinkedListNode <T> AddFirst(T value) => linkedList.AddFirst(value);
public void Push(T item) { // this is the first come first out // we add the first _list.AddFirst(item); }
public bool MoveNext() { // Debug.WriteLine("calling PropertyNameEnumerator.MoveNext"); while (_dobject != null) { var array = _dobject as mdr.DArray; if (array != null) { while (++_elementsIndex < array.ElementsLength) { if (!_visiteds.Contains(-_elementsIndex)) { _visiteds.Add(-_elementsIndex); _current = _elementsIndex.ToString(); return(true); } } } /* * ///Spec says the order of retreiving the properties does not matter, so the following code is faster * ///However some stupid websites (e.g. BBC) count on the fact that Browsers list properties with a certain order * ///So, we had to change to the slower to be browser compatible, rather than spec compatible * if (_map == null) * _map = _dobject.Map; * * while (_map != null) * { * var prop = _map.Property; * _map = _map.Parent; * * if (!prop.IsNotEnumerable && !_visiteds.Contains(prop.NameId)) * { * _visiteds.Add(prop.NameId); * _current = prop.Name; * return true; * } * } * _dobject = _dobject.Prototype; * _elementsIndex = -1; * _current = null; */ if (_currentNode == null) { //We may have reached to the end of collected properties, but meanwhile some new ones may have been added _propNames.Clear(); if (_map != null && _map != _dobject.Map) { _map = _dobject.Map; } for (var m = _dobject.Map; m != _map; m = m.Parent) { var prop = m.Property; if (!prop.IsNotEnumerable && !_visiteds.Contains(prop.NameId)) { _visiteds.Add(prop.NameId); _propNames.AddFirst(prop.Name); } } _map = _dobject.Map; _currentNode = _propNames.First; if (_currentNode == null) { _dobject = _dobject.Prototype; _elementsIndex = -1; _current = null; _map = null; continue; //Jump to begining of the loop! } } _current = _currentNode.Value; _currentNode = _currentNode.Next; return(true); } return(false); }
static void Main(string[] args) { IncreaseCost[] applications = new IncreaseCost[4]; IncreaseCost app0 = new Game("Heroes3", 15, 200, "No license"); IncreaseCost app1 = new Game("Disciples", 5, 500, "Official license"); IncreaseCost app2 = new Software("Util_1", 0, 30); IncreaseCost app3 = new Software("Util_1", 0, 40); applications[0] = app0; applications[1] = app1; applications[2] = app2; applications[3] = app3; list1.AddRange(applications); list2.AddFirst(app0); list2.AddAfter(list2.First, app1); list2.AddLast(app2); list2.AddAfter(list2.Last, app3); //list1.Add(new Game("Heroes3", 15, 200, "No license")); int flag = 100; while (flag != 0) { Console.Clear(); Console.WriteLine("Меню : "); Console.WriteLine("1 – просмотр коллекции"); Console.WriteLine("2 – добавление элемента (используйте конструктор с 1-2 параметрами)"); Console.WriteLine("3 – добавление элемента по указанному индексу"); Console.WriteLine("4 – нахождение элемента с начала коллекции (переопределить метод Equals или оператор == для вашего класса – сравнение только по полю name)"); Console.WriteLine("5 – нахождение элемента с конца коллекции"); Console.WriteLine("6 – удаление элемента по индексу"); Console.WriteLine("7 – удаление элемента по значению"); Console.WriteLine("8 – реверс коллекции"); Console.WriteLine("9 – сортировка"); Console.WriteLine("10 – выполнение методов всех объектов, поддерживающих Interface2"); Console.WriteLine("11 – LinkedList просмотр коллекции"); Console.WriteLine("12 – LinkedList добавление элемента (используйте конструктор с 1-2 параметрами)"); Console.WriteLine("13 – LinkedList добавление элемента по указанному индексу"); Console.WriteLine("14 – LinkedList нахождение элемента с начала коллекции (переопределить метод Equals или оператор == для вашего класса – сравнение только по полю name)"); Console.WriteLine("15 – LinkedList нахождение элемента с конца коллекции"); Console.WriteLine("16 – LinkedList удаление элемента по индексу"); Console.WriteLine("17 – LinkedList удаление элемента по значению"); Console.WriteLine("18 – LinkedList реверс коллекции"); Console.WriteLine("19 – LinkedList сортировка"); Console.WriteLine("20 – LinkedList выполнение методов всех объектов, поддерживающих Interface2"); Console.WriteLine("0 – выход"); flag = Convert.ToInt32(Console.ReadLine()); switch (flag) { //просмотр коллекции case (1): { Console.Clear(); if (Program.list1.Count > 0) { Console.WriteLine("list1 содержит : " + list1.Count); foreach (Object obj in Program.list1) { Console.WriteLine("************************************************************"); Console.WriteLine(obj.ToString()); } } else { Console.WriteLine("list1 пустой"); } Console.ReadLine(); break; } //добавление элемента case (2): { Console.Clear(); Console.WriteLine("Теперь создаем обьект"); Console.WriteLine("Введите name"); String name = Console.ReadLine(); Console.WriteLine("Введите bugs"); int bugs = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Введите cost"); double cost = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Введите licenseAgreement"); String licenseAgreement = Console.ReadLine(); if (licenseAgreement.Equals("0")) { list1.Add(new Software(name, bugs, cost)); Console.WriteLine("Done"); Console.WriteLine("создали Software"); } else { list1.Add(new Game(name, bugs, cost, licenseAgreement)); Console.WriteLine("Done"); Console.WriteLine("создали Game"); } Console.WriteLine("И добавили в list1"); Console.ReadLine(); break; } //добавление элемента по указанному индексу case (3): { Console.Clear(); try { Console.WriteLine("Теперь создаем обьект"); Console.WriteLine("Введите name"); String name = Console.ReadLine(); Console.WriteLine("Введите bugs"); int bugs = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Введите cost"); double cost = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Введите licenseAgreement"); String licenseAgreement = Console.ReadLine(); Console.WriteLine("Введите index"); int index = Convert.ToInt32(Console.ReadLine()); if (licenseAgreement.Equals("0")) { list1.Insert(index, new Software(name, bugs, cost)); Console.WriteLine("Done"); Console.WriteLine("создали Software"); } else { list1.Insert(index, new Game(name, bugs, cost, licenseAgreement)); Console.WriteLine("Done"); Console.WriteLine("создали Game"); } Console.WriteLine("И добавили в list1"); } catch (Exception ex) { Console.WriteLine("Не могу выполнить"); } Console.ReadLine(); break; } //нахождение элемента с начала коллекции case (4): { Console.Clear(); Console.WriteLine("Находим элемент по имени name с начала"); Console.WriteLine("Введите name"); String name = Console.ReadLine(); Software finding = null; for (int i = 0; i < list1.Count; i++) { if (name.Equals(((Software)list1[i]).getName())) { finding = (Software)list1[i]; break; } } if (finding != null) { Console.WriteLine("Нашел"); if (finding is Game) { Console.WriteLine(((Game)finding).ToString()); } else { Console.WriteLine(((Software)finding).ToString()); } } else { Console.WriteLine("Не нашел"); } Console.ReadLine(); break; } //нахождение элемента с конца коллекции case (5): { Console.Clear(); Console.WriteLine("Находим элемент по имени name с конца"); Console.WriteLine("Введите name"); String name = Console.ReadLine(); Software finding = null; for (int i = list1.Count - 1; i >= 0; i--) { if (name.Equals(((Software)list1[i]).getName())) { finding = (Software)list1[i]; break; } } if (finding != null) { Console.WriteLine("Нашел"); if (finding is Game) { Console.WriteLine(((Game)finding).ToString()); } else { Console.WriteLine(((Software)finding).ToString()); } } else { Console.WriteLine("Не нашел"); } Console.ReadLine(); break; } //удаление элемента по индексу case (6): { Console.Clear(); try { Console.WriteLine("Удалим элемент по индексу"); Console.WriteLine("Введите индекс"); int index = Convert.ToInt32(Console.ReadLine()); list1.RemoveAt(index); Console.WriteLine("Эх жаль элемента"); } catch (Exception ex) { Console.WriteLine("Че-то пошло не так :)"); } Console.ReadLine(); break; } //удаление элемента по значению case (7): { Console.Clear(); try { Console.WriteLine("Удалим элемент по значению"); Console.WriteLine("Введите name"); String name = Console.ReadLine(); for (int i = 0; i < list1.Count; i++) { if (name.Equals(((Software)list1[i]).getName())) { list1.RemoveAt(i); Console.WriteLine("Эх жаль элемента"); break; } } } catch (Exception ex) { Console.WriteLine("Че-то пошло не так :)"); } Console.ReadLine(); break; } //реверс коллекции case (8): { Console.Clear(); Console.WriteLine("Произведем реверс list1"); list1.Reverse(); Console.WriteLine("Готово :)"); Console.ReadLine(); break; } //сортировка case (9): { Console.Clear(); Console.WriteLine("Отсортируем по name list1"); list1.Sort(); Console.WriteLine("Готово )"); Console.ReadLine(); break; } //выполнение методов всех объектов, поддерживающих Interface2 case (10): { Console.Clear(); foreach (IncreaseCost obj in list1) { if (obj is DecreaseCost) { Console.WriteLine("Ура"); Console.WriteLine("************************************************************"); ((DecreaseCost)obj).decreaseCost(); ((DecreaseCost)obj).information(); ((DecreaseCost)obj).statistic(); ((DecreaseCost)obj).info(); } } Console.ReadLine(); break; } //LinkedList просмотр коллекции case (11): { Console.Clear(); if (Program.list2.Count > 0) { Console.WriteLine("list2 содержит : " + list2.Count); foreach (Object obj in Program.list2) { Console.WriteLine("************************************************************"); Console.WriteLine(obj.ToString()); } } else { Console.WriteLine("list2 пустой"); } Console.ReadLine(); break; } //LinkedList добавление элемента case (12): { Console.Clear(); Console.WriteLine("Теперь создаем обьект"); Console.WriteLine("Введите name"); String name = Console.ReadLine(); Console.WriteLine("Введите bugs"); int bugs = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Введите cost"); double cost = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Введите licenseAgreement"); String licenseAgreement = Console.ReadLine(); if (licenseAgreement.Equals("0")) { list2.AddFirst(new Software(name, bugs, cost)); Console.WriteLine("Done"); Console.WriteLine("создали Software"); } else { list2.AddFirst(new Game(name, bugs, cost, licenseAgreement)); Console.WriteLine("Done"); Console.WriteLine("создали Game"); } Console.WriteLine("И добавили в list2"); Console.ReadLine(); break; } //LinkedList добавление элемента по указанному индексу case (13): { Console.Clear(); try { Console.WriteLine("Теперь создаем обьект"); Console.WriteLine("Введите name"); String name = Console.ReadLine(); Console.WriteLine("Введите bugs"); int bugs = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Введите cost"); double cost = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Введите licenseAgreement"); String licenseAgreement = Console.ReadLine(); Console.WriteLine("Введите index обьекта после котрого вставим этот"); int index = Convert.ToInt32(Console.ReadLine()); IncreaseCost obj = list2.ElementAt(index); if (licenseAgreement.Equals("0")) { list2.AddAfter(list2.Find(obj), new Software(name, bugs, cost)); Console.WriteLine("Done"); Console.WriteLine("создали Software"); } else { list2.AddAfter(list2.Find(obj), new Game(name, bugs, cost, licenseAgreement)); Console.WriteLine("Done"); Console.WriteLine("создали Game"); } Console.WriteLine("И добавили в list2"); } catch (Exception ex) { Console.WriteLine("Не могу выполнить"); } Console.ReadLine(); break; } //LinkedList нахождение элемента с начала коллекции case (14): { Console.Clear(); Console.WriteLine("Находим элемент по имени name с начала"); Console.WriteLine("Введите name"); String name = Console.ReadLine(); Software finding = null; LinkedListNode <IncreaseCost> node = list2.First; for (int i = 0; i < list2.Count; i++) { IncreaseCost obj = node.Value; if (name.Equals(((Software)obj).getName())) { finding = (Software)obj; } node = node.Next; } if (finding != null) { Console.WriteLine("Нашел"); if (finding is Game) { Console.WriteLine(((Game)finding).ToString()); } else { Console.WriteLine(((Software)finding).ToString()); } } else { Console.WriteLine("Не нашел"); } Console.ReadLine(); break; } //LinkedList нахождение элемента с конца коллекции case (15): { Console.Clear(); Console.WriteLine("Находим элемент по имени name с начала"); Console.WriteLine("Введите name"); String name = Console.ReadLine(); Software finding = null; LinkedListNode <IncreaseCost> node = list2.Last; for (int i = 0; i < list2.Count; i++) { IncreaseCost obj = node.Value; if (name.Equals(((Software)obj).getName())) { finding = (Software)obj; } node = node.Previous; } if (finding != null) { Console.WriteLine("Нашел"); if (finding is Game) { Console.WriteLine(((Game)finding).ToString()); } else { Console.WriteLine(((Software)finding).ToString()); } } else { Console.WriteLine("Не нашел"); } Console.ReadLine(); break; } //LinkedList удаление элемента по индексу case (16): { Console.Clear(); try { Console.WriteLine("Удалим элемент по индексу"); Console.WriteLine("Введите индекс"); int index = Convert.ToInt32(Console.ReadLine()); list2.Remove(list2.ElementAt(index)); Console.WriteLine("Эх жаль элемента"); } catch (Exception ex) { Console.WriteLine("Че-то пошло не так :)"); } Console.ReadLine(); break; } //LinkedList удаление элемента по значению case (17): { Console.Clear(); try { Console.WriteLine("Удалим элемент по значению"); Console.WriteLine("Введите name"); String name = Console.ReadLine(); LinkedListNode <IncreaseCost> node = list2.First; for (int i = 0; i < list2.Count; i++) { IncreaseCost obj = node.Value; if (name.Equals(((Software)obj).getName())) { list2.Remove(obj); Console.WriteLine("Эх жаль элемента"); break; } node = node.Next; } } catch (Exception ex) { Console.WriteLine("Че-то пошло не так :)"); } Console.ReadLine(); break; } //LinkedList реверс коллекции case (18): { Console.Clear(); Console.WriteLine("Произведем реверс list2"); IncreaseCost[] array = list2.ToArray(); LinkedList <IncreaseCost> list3 = new LinkedList <IncreaseCost>(); foreach (IncreaseCost obj in list2) { list3.AddFirst(obj); } list2 = list3; Console.WriteLine("Готово :)"); Console.ReadLine(); break; } //LinkedList сортировка case (19): { Console.Clear(); Console.WriteLine("Отсортируем по name list2"); IncreaseCost[] array = new IncreaseCost[list2.Count]; int i = 0; foreach (IncreaseCost obj in list2) { array[i] = obj; i++; } Array.Sort(array); list2.Clear(); for (int q = 0; q < array.Length; q++) { list2.AddLast(array[q]); } Console.WriteLine("Готово )"); Console.ReadLine(); break; } //выполнение методов всех объектов, поддерживающих Interface2 case (20): { Console.Clear(); foreach (IncreaseCost obj in list2) { if (obj is DecreaseCost) { Console.WriteLine("Ура"); Console.WriteLine("************************************************************"); ((DecreaseCost)obj).decreaseCost(); ((DecreaseCost)obj).information(); ((DecreaseCost)obj).statistic(); ((DecreaseCost)obj).info(); } } Console.ReadLine(); break; } case (0): { Console.Clear(); break; } } } }
protected void AddFirst(ref T data) { LinkedList.AddFirst(data); }
private System.Collections.Generic.LinkedList <State> GetPred(State u) { var s = new System.Collections.Generic.LinkedList <State>(); State tempState; tempState = new State(u.X + 1, u.Y, new Pair <double, double>(-1, -1)); if (!Occupied(tempState)) { s.AddFirst(tempState); } if (allowDiagonalPathing) { tempState = new State(u.X + 1, u.Y + 1, new Pair <double, double>(-1, -1)); if (!Occupied(tempState)) { s.AddFirst(tempState); } } tempState = new State(u.X, u.Y + 1, new Pair <double, double>(-1, -1)); if (!Occupied(tempState)) { s.AddFirst(tempState); } if (allowDiagonalPathing) { tempState = new State(u.X - 1, u.Y + 1, new Pair <double, double>(-1, -1)); if (!Occupied(tempState)) { s.AddFirst(tempState); } } tempState = new State(u.X - 1, u.Y, new Pair <double, double>(-1, -1)); if (!Occupied(tempState)) { s.AddFirst(tempState); } if (allowDiagonalPathing) { tempState = new State(u.X - 1, u.Y - 1, new Pair <double, double>(-1, -1)); if (!Occupied(tempState)) { s.AddFirst(tempState); } } tempState = new State(u.X, u.Y - 1, new Pair <double, double>(-1, -1)); if (!Occupied(tempState)) { s.AddFirst(tempState); } if (allowDiagonalPathing) { tempState = new State(u.X + 1, u.Y - 1, new Pair <double, double>(-1, -1)); if (!Occupied(tempState)) { s.AddFirst(tempState); } } return(s); }
/// <summary> /// Does a search for a path from start to finish on /// graph using given search type /// </summary> /// <param name="start">start value</param> /// <param name="finish">finish value</param> /// <param name="graph">graph to search</param> /// <returns>string for path or empty string if there is no path</returns> string Search(int start, int finish, Graph <int> graph, SearchType searchType) { System.Collections.Generic.LinkedList <GraphNode <int> > searchList = new System.Collections.Generic.LinkedList <GraphNode <int> >(); //Special case for start and finish the same if (start == finish) { return(start.ToString()); } else if (graph.Find(start) == null || graph.Find(finish) == null) { //Start or finish not in graph return(""); } else { //Add start node to dictionary and search list GraphNode <int> startNode = graph.Find(start); Dictionary <GraphNode <int>, PathNodeInfo <int> > pathNodes = new Dictionary <GraphNode <int>, PathNodeInfo <int> >(); pathNodes.Add(startNode, new PathNodeInfo <int>(null)); searchList.AddFirst(startNode); //Loop until we exhaust all possible paths while (searchList.Count > 0) { //Extract front of search list GraphNode <int> currentNode = searchList.First.Value; print("Current Node: " + currentNode.Value); searchList.RemoveFirst(); //Explore each neighbor of this node foreach (GraphNode <int> neighbor in currentNode.Neighbors) { //Check for found finish if (neighbor.Value == finish) { pathNodes.Add(neighbor, new PathNodeInfo <int>(currentNode)); return(ConvertPathToString(neighbor, pathNodes)); } else if (pathNodes.ContainsKey(neighbor)) { //Found a cycle, so skip this neighbor continue; } else { //Link neighbor to current node in path pathNodes.Add(neighbor, new PathNodeInfo <int>(currentNode)); //Add neighbor to front or back of search list if (searchType == SearchType.DepthFirst) { searchList.AddFirst(neighbor); } else { searchList.AddLast(neighbor); } print("Just added " + neighbor.Value + " to search list"); } } } //Didn't find a path from start to finish return(""); } }
// On error or failure, returns null. private static string locate_fxc_on_disk() { try { long EndTime = DateTime.Now.Ticks + MAX_LOCATE_TIME; // Paths to process System.Collections.Generic.LinkedList<string> PathQueue = new System.Collections.Generic.LinkedList<string>(); // Path already processed in form Key=Path, Value="1" System.Collections.Specialized.StringDictionary Processed = new System.Collections.Specialized.StringDictionary(); // Add default paths // - Program files PathQueue.AddLast(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)); // - Hard disks foreach (DriveInfo Drive in DriveInfo.GetDrives()) if (Drive.DriveType == DriveType.Fixed) PathQueue.AddLast(Drive.RootDirectory.Name); // Processing loop - berform breadth first search (BFS) algorithm while (PathQueue.Count > 0) { // Get directory to process string Dir = PathQueue.First.Value; PathQueue.RemoveFirst(); // Already processed if (Processed.ContainsKey(Dir)) continue; // Add to processed Processed.Add(Dir, "1"); try { // Look for fxc.exe file string[] FxcFiles = Directory.GetFiles(Dir, "fxc.exe"); if (FxcFiles.Length > 0) return FxcFiles[0]; // Look for subdirectories foreach (string SubDir in Directory.GetDirectories(Dir)) { // Interesting directory - add at the beginning of the queue if (DirectoryIsInteresting(SubDir)) PathQueue.AddFirst(SubDir); // Not interesting - add at the end of the queue else PathQueue.AddLast(SubDir); } } catch (Exception ) { } // Time out if (DateTime.Now.Ticks >= EndTime) return null; } // Not found return null; } catch (Exception ) { return null; } }