Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Collections;
- namespace Stack_LinkedList
- {
- internal class Program
- {
- static void Main(string[] args)
- {
- NodeStack<string> stack = new NodeStack<string>();
- stack.Push("tom");
- stack.Push("sam");
- stack.Push("max");
- stack.Push("kirill");
- foreach(string s in stack)
- {
- Console.WriteLine(s);
- }
- Console.WriteLine();
- string header = stack.Peek();
- Console.WriteLine($"верхушка стека: {header}");
- Console.WriteLine();
- header = stack.Pop();
- foreach(string s in stack)
- {
- Console.WriteLine(s);
- }
- }
- public class Node<T>//создание узла
- {
- public Node(T data)
- {
- Data = data;
- }
- public T Data { get; set; }
- public Node<T> Next { get; set; }
- }
- public class NodeStack<T> : IEnumerable<T>
- {
- Node<T> head;
- int count;
- public bool IsEmpty
- {
- get { return count == 0; }
- }
- public int Count
- {
- get { return count; }
- }
- public void Push(T item)
- {
- //увеличиваем стек
- Node<T> node = new Node<T>(item);
- node.Next = head;//переустанавливаем верхушку стека
- head = node;
- count++;
- }
- public T Pop()
- {
- if(IsEmpty)
- {
- throw new InvalidOperationException("стек пуст");
- }
- Node<T> temp = head;
- head = head.Next;//переустанавливаем верхушку стека
- count--;
- return temp.Data;
- }
- public T Peek()
- {
- if(IsEmpty)
- {
- throw new InvalidOperationException("стек пуст");
- }
- return head.Data;
- }
- //создание интерфейса
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ((IEnumerable)this).GetEnumerator();
- }
- IEnumerator<T> IEnumerable<T>.GetEnumerator()
- {
- Node<T> current = head;
- while(current != null)
- {
- yield return current.Data;
- current = current.Next;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement