Создать свой стек и сделать в нем сортировку - C#
Формулировка задачи:
Всем доброго времени суток!!!
Помогите создать свой стек и сделать в нем сортировку, просто тот стек который есть в C# не подходит, так как по моему заданию его нельзя использовать.
Буду благодарен
Решение задачи: «Создать свой стек и сделать в нем сортировку»
textual
Листинг программы
using System;
using System.Text;
namespace ConsoleApplication18
{
class Program
{
class Node
{
public int val;
public Node next;
public Node prev;
}
class Stack
{
private Node root;
private Node top;
public void Push(int _val)
{
if (root == null)
{
root = new Node();
root.val = _val;
top = root;
}
else
{
top.next = new Node();
top.next.val = _val;
top.next.prev = top;
top = top.next;
}
}
public int Pop(int _val)
{
int result;
if (root == null)
{
Console.WriteLine("Error: stack is empty");
}
else if (root == top)
{
result = root.val;
root = null;
return result;
}
result = top.val;
top = top.prev;
top.next = null;
return result;
}
private Node ElementAt(int num)
{
if (root != null && num > -1)
{
int c = 0;
Node current = root;
while (c < num)
{
c++;
current = current.next;
}
return current;
}
return null;
}
private int Count()
{
int c = 0;
if (root != null)
{
Node current = root;
while (current != top)
{
c++;
current = current.next;
}
c++;
}
return c;
}
public void Sort()
{
int n = this.Count();
int step = n / 2;
int j;
while (step > 0)
{
for (int i = 0; i < (n - step); i++)
{
j = i;
while (j >= 0 && this.ElementAt(j).val > this.ElementAt(j + step).val)
{
Node first = this.ElementAt(j);
Node second = this.ElementAt(j + step);
int buf = first.val;
first.val = second.val;
second.val = buf;
j--;
}
}
step /= 2;
}
}
public void Print()
{
if (root == null)
{
Console.WriteLine("Stack is empty");
return;
}
Node i = root;
while (i != top)
{
Console.Write(i.val.ToString() + " ");
i = i.next;
}
Console.WriteLine(top.val.ToString());
}
}
public static void Main(string[] args)
{
Stack stack = new Stack();
stack.Push(5);
stack.Push(3);
stack.Push(7);
stack.Push(2);
stack.Push(1);
stack.Print();
stack.Sort();
stack.Print();
Console.ReadKey();
Console.ReadKey();
}
}
}