Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Nodes
- {
- class LinkedListUtils
- {
- public static Node<T> createList<T>(T[] valuesArray)
- {
- Node<T> current = null;
- for (int i = valuesArray.Length - 1; i >= 0; i--)
- {
- if (current != null)
- current = new Node<T>(valuesArray[i], current);
- else
- current = new Node<T>(valuesArray[i]);
- }
- return current;
- }
- public static Node<T> leaveOnly<T>(Node<T> pos, Predicate<Node<T>> condition)
- {
- Node<T> first = null,
- lastValid = null;
- while (pos != null)
- {
- if (condition(pos)) // if the elements meets the condition
- {
- if (first == null) // if first element was not set yet, set it to the one found now
- first = pos;
- else // if a first element was set already, add pointer to last element
- lastValid.setNext(pos);
- lastValid = pos;
- }
- pos = pos.getNext(); // move to next element
- }
- return first;
- }
- public static Node<T> remove<T>(Node<T> pos, Predicate<Node<T>> condition)
- {
- return leaveOnly<T>(pos,
- node => !condition(node) // lambda expression for making a 'not' predicate
- );
- }
- public static string toString<T>(Node<T> pos)
- {
- string list = "[";
- while (pos != null)
- {
- // add comma if there is more than one element
- if (list.Length != 1)
- list += ", ";
- // add value to string
- list += pos.getValue();
- // move to next element
- pos = pos.getNext();
- }
- list += "]"; // close list
- return list;
- }
- public static void print<T>(Node<T> pos)
- {
- Console.Write(toString<T>(pos));
- }
- public static void println<T>(Node<T> pos)
- {
- Console.WriteLine(toString<T>(pos));
- }
- public static Node<int> createNumbersList(int start, int end, int step = 1)
- {
- if ((end - start) * step < 0) // if there's no way to reach the end with the step given
- return null;
- // initialize variables
- Node<int> first = null, // first element of the list
- pos = null; // the current position
- int current = start;
- // while steps have not reached the destination
- while (
- (end >= start && current <= end) ||
- start > end && current >= end
- )
- {
- if (first == null) // set first element if needed
- {
- first = new Node<int>(current);
- pos = first;
- }
- else
- {
- pos.setNext(new Node<int>(current));
- pos = pos.getNext();
- }
- current += step;
- }
- return first;
- }
- public static int listLength<T>(Node<T> list)
- {
- int counter = 0;
- Node<T> pos = list;
- while (pos != null)
- {
- counter++;
- pos = pos.getNext();
- }
- return counter;
- }
- }
- }
Add Comment
Please, Sign In to add comment