Стек через LinkedList - C#
Формулировка задачи:
Доброго времени суток.
Необходим реализовать стек и очередь, через LinkedList.
Я знаю, что в C# есть для этого отдельные классы и всё такое, но лабораторная работа требует именно так и никак иначе.
Короче нашел, код в нете, вот первоисточник: http://evilcoderr.blogspot.com/2013/01/doubly-linked-list-c.html
Я немного подправил код, но вот выяснилось новая "фича".
При задание количества элементов стека, очереди, в результате выводит меньшее количество элементов (в 2 раза меньше), результат работы на скрине:
Я уже ставил брекпоинты, но но всё равно не могу понять почему оно сбивает значение и главное где??
Вот код реализации
Вот ссылка на сам проект: https://drive.google.com/folderview?...DQ&usp=sharing
namespace Lab_2
{
class Program
{
static void Main(string[] args)
{
Doubly_Linked_List queue = new Doubly_Linked_List();
Console.WriteLine("Реализация очереди.");
Console.WriteLine("Укажите количество елементов стека: ");
queue.Count = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Стек");
for (int i = 0; i < queue.Count; i++)
{
queue.Push_Front(Console.ReadLine());
}
queue.Display();
Console.ReadLine();
}
}
}namespace Lab_2
{
class Doubly_Linked_List
{
private Node First; //первый
private Node Current;//текущий
private Node Last;//последний
private int size; //размер
public Doubly_Linked_List()
{
size = 0;
First = Current = Last = null;
}
public int Count //свойство для size
{
get { return size; }
set { size = value; }
}
public bool isEmpty //проверка на пустоту
{
get
{
return size == 0;
}
}
public void Insert_Index(object newElement, int index) //вставить по индекусу
{
if (index < 1 || index > size) //вброс ошибки, если неправильный индекс
{
throw new InvalidOperationException();
}
else if (index == 1) //если начало
{
Push_Front(newElement);
}
else if (index == size) //если конец
{
Push_Back(newElement);
}
else //иначе ищем элемент с таким индексом
{
int count = 1;
Current = First;
while (Current != null && count != index)
{
Current = Current.Next;
count++;
}
Node newNode = new Node(newElement); //создаем объект
Current.Prev.Next = newNode;
newNode.Prev = Current.Prev;
Current.Prev = newNode;
newNode.Next = Current;
}
}
public void Push_Front(object newElement)//добавить елементы в начало списка
{
Node newNode = new Node(newElement);
if (First == null)
{
First = Last = newNode;
}
else
{
newNode.Next = First;
First = newNode; //First и newNode указывают на один и тот же объект
newNode.Next.Prev = First;
}
Count--;//было Count++
}
public Node Pop_Front()//удалять елменты из начала списка
{
if (First == null)
{
throw new InvalidOperationException();
}
else
{
Node temp = First;
if (First.Next != null)
{
First.Next.Prev = null;
}
First = First.Next;
Count--;
return temp;
}
}
public void Push_Back(object newElement)//Добавляет елементы с конца списка
{
Node newNode = new Node(newElement);
if (First == null)
{
First = Last = newNode;
}
else
{
Last.Next = newNode;
newNode.Prev = Last;
Last = newNode;
}
Count--;//было Count++
}
public Node Pop_Back()//удаляет елемент с конца списка
{
if (Last == null)
{
throw new InvalidOperationException();
}
else
{
Node temp = Last;
if (Last.Prev != null)
{
Last.Prev.Next = null;
}
Last = Last.Prev;
Count--;//было Count--
return temp;
}
}
public void ClearList() //полностью очистить список
{
while (!isEmpty)
{
Pop_Front();
}
}
public void Display() //вывести в прямом порядке
{
if (First == null)
{
Console.WriteLine("Двунаправленный список пуст");
return;
}
Current = First;
int count = 1;
while (Current != null)
{
Console.WriteLine("Елемент " + count.ToString() + " : " + Current.Value.ToString());
count++;
Current = Current.Next;
}
}
public void ReverseDisplay() //вывести в обратном порядке
{
if (Last == null)
{
Console.WriteLine("Doubly Linked List is empty");
return;
}
Current = Last;
int count = 1;
while (Current != null)
{
Console.WriteLine("Element " + count.ToString() + " : " + Current.Value.ToString());
count++;
Current = Current.Prev;
}
}
public void DeleteElement(int index)
{ //удалить элемент по индексу
if (index < 1 || index > size)
{
throw new InvalidOperationException();
}
else if (index == 1)
{
Pop_Front();
}
else if (index == size)
{
Pop_Back();
}
else
{
int count = 1;
Current = First;
while (Current != null && count != index)
{
Current = Current.Next;
count++;
}
Current.Prev.Next = Current.Next;
Current.Next.Prev = Current.Prev;
}
}
public Node FindNode(object Data) //найти Node и вернуть его
{
Current = First;
while (Current != null)
{
Current = Current.Next;
}
return Current;
}
public int GetIndex(object Data) //достать индекс по значению элемента
{
Current = First;
int index = 1;
while (Current != null)
{
Current = Current.Next;
index++;
}
return index;
} }}Решение задачи: «Стек через LinkedList»
textual
Листинг программы
using System;
using System.Collections.Generic;
namespace ConsoleApplication198
{
class Program
{
static void Main(string[] args)
{
//создаем
var stackQueue = new StackQueue<int>();
Console.Write("Укажите количество элементов стека: ");
var count = int.Parse(Console.ReadLine());
for (int i = 0; i < count; i++)
stackQueue.Push(int.Parse(Console.ReadLine()));
var temp = stackQueue.Dequeue();
Console.WriteLine("Dequeue: " + temp);
temp = stackQueue.Pop();
Console.WriteLine("Pop: " + temp);
//выводим
Console.WriteLine("Rest: ");
foreach (var val in stackQueue)
Console.WriteLine(val);
Console.ReadLine();
}
}
class StackQueue<T> : IEnumerable<T>
{
private readonly LinkedList<T> list = new LinkedList<T>();
//stack's push
public void Push(T val)
{
list.AddLast(val);
}
//stack's pop
public T Pop()
{
var res = list.Last;
list.RemoveLast();
return res.Value;
}
//enqueue
public void Enqueue(T val)
{
Push(val);
}
//dequeue
public T Dequeue()
{
var res = list.First;
list.RemoveFirst();
return res.Value;
}
public IEnumerator<T> GetEnumerator()
{
foreach (var val in list)
yield return val;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}