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 Vezba_04_2017
- {
- class GenericStack<T>
- {
- class GenericStackNode<T>
- {
- public GenericStackNode(T t)
- {
- Content = t;
- Next = null;
- }
- public T Content { get; set; }
- public GenericStackNode<T> Next { get; set; }
- }
- private GenericStackNode<T> _head;
- public int Lenght
- {
- get
- {
- int lenght = 0;
- GenericStackNode<T> current = _head;
- while(current != null)
- {
- current = current.Next;
- lenght++;
- }
- return lenght;
- }
- }
- public bool IsEmpty
- {
- get { return _head == null; }
- }
- public T this[int index]
- {
- get
- {
- return GetNode(index).Content;
- }
- set
- {
- GetNode(index).Content = value;
- }
- }
- private GenericStackNode<T> GetNode(int index)
- {
- if (index < 0 || index >= Lenght)
- throw new IndexOutOfRangeException();
- GenericStackNode<T> current = _head;
- for (int i = 0; i < index; i++)
- current = current.Next;
- return current;
- }
- public void AddFirst(T content)
- {
- GenericStackNode<T> newNode = new GenericStackNode<T>(content);
- newNode.Next = _head;
- _head = newNode;
- }
- public void AddLast(T content)
- {
- if (IsEmpty)
- AddFirst(content);
- else
- {
- GenericStackNode<T> newNode = new GenericStackNode<T>(content);
- GenericStackNode<T> currentNode = _head;
- while (currentNode.Next != null)
- {
- currentNode = currentNode.Next;
- }
- currentNode.Next = newNode;
- }
- }
- public void RemoveFirst()
- {
- if (!IsEmpty)
- _head = _head.Next;
- else
- throw new InvalidOperationException();
- }
- public void RemoveLast()
- {
- if(!IsEmpty)
- {
- if (_head.Next == null)
- _head = null;
- else
- {
- GenericStackNode<T> node = _head;
- while (node.Next.Next != null)
- node = node.Next;
- node.Next = null;
- }
- }
- }
- public void InsertAt(T content, int index)
- {
- if (index < 0 || index >= Lenght)
- throw new IndexOutOfRangeException();
- if (index == 0)
- AddFirst(content);
- else if (index == Lenght)
- AddLast(content);
- else
- {
- GenericStackNode<T> newNode = new GenericStackNode<T>(content);
- GenericStackNode<T> previousNode = GetNode(index - 1);
- newNode.Next = previousNode.Next;
- previousNode.Next = newNode;
- }
- }
- public void Clear()
- {
- _head = null;
- }
- public int IndexOf(T content)
- {
- GenericStackNode<T> newNode = new GenericStackNode<T>(content);
- for (int i = 0; i < Lenght; i++)
- {
- if (_head == newNode)
- return i;
- _head = _head.Next;
- }
- return -1;
- }
- public override string ToString()
- {
- StringBuilder sb = new StringBuilder();
- GenericStackNode<T> node = _head;
- while (node != null)
- {
- sb.Append(node.Content);
- sb.Append(" -> ");
- node = node.Next;
- }
- sb.Append("*");
- return sb.ToString();
- }
- }
- }
Add Comment
Please, Sign In to add comment