Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace MyList
- {
- public class Node<T>
- {
- public Node<T> Next { get; set; }
- public T Value { get; set; }
- public Node(T value)
- {
- Value = value;
- }
- }
- public class MyList<T>
- {
- private const string MsgError =
- "Index was out of range. Must be non-negative and less than the size of the collection. ";
- private Node<T> _head;
- private int _count;
- public int Count
- {
- get => _count;
- }
- public T this[int index]
- {
- get
- {
- if (index >= Count || index < 0)
- throw new ArgumentOutOfRangeException(
- MsgError);
- Node<T> ret = _head;
- for (int i = 0; i < index; i++)
- {
- ret = ret.Next;
- }
- return ret.Value;
- }
- set
- {
- if (index >= Count || index < 0)
- throw new ArgumentOutOfRangeException(
- MsgError);
- Node<T> ret = _head;
- for (int i = 0; i < index; i++)
- {
- ret = ret.Next;
- }
- ret.Value = value;
- }
- }
- public void Clear()
- {
- _head = null;
- _count = 0;
- }
- public void RemoveAt(int index)
- {
- if (index >= _count || index < 0)
- throw new ArgumentOutOfRangeException(
- MsgError);
- if (index == 0)
- {
- _head = _head.Next;
- }
- else
- {
- Node<T> node = _head;
- for (int i = 0; i < index - 1; i++)
- {
- node = node.Next;
- }
- node.Next = node.Next?.Next;
- }
- _count--;
- }
- public void Add(T value)
- {
- if (_head == null)
- {
- _head = new Node<T>(value);
- }
- else
- {
- Node<T> temp = _head;
- while (temp.Next != null)
- {
- temp = temp.Next;
- }
- temp.Next = new Node<T>(value);
- }
- _count++;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement