@Darek554:
czy dobrze naskrobałem kod, tzn. czy napisałem go zgodnie z założeniami zadania?
Można odpowiedzieć, że Idziesz w dobrą stronę, ale stos to jeszcze nie jest:).
push
jest źle zaimplementowana: bierze jako argument obiekt klasy Element
(!?!), przecież użytkownik będzie chciał sobie wrzucać i ściągać ze stosu stringi;
pop
nie zwraca elementu, nie Masz też innego sposobu dostania się do szczytu stosu, więc jak user ma użyć tych stringów, które sobie tam wrzucił? Brakuje metody sprawdzającej czy stos jest pusty, isEmpty
, która jest niezbędna do używania strukturki: ściągaj ze stosu dopóki nie pusty, jesli pusty to coś tam, etc... Mozna też dołożyć metodę peek
, która nie zrzuca ze stosu, tylko "podgląda" pierwszy element. Acha, cały świat nazywa wskaźnik do następnego elementu listy next
, a u Ciebie poprzedni
WTF? Przeanalizuj sobie taki przykładowy kod stosu:
using System;
class LinkedListStack{
internal Element head;
internal class Element {
internal string key;
public Element next;
public Element(string e) {
this.key = e;
}
}
public LinkedListStack() {
head = null;
}
public void push(string e) {
Element head_old = head;
head = new Element(e);
head.next = head_old;
}
public string peek() {
// exception if empty!
return head.key;
}
public string pop() {
// exception if empty!
string e = head.key;
head = head.next;
return e;
}
public bool isEmpty() {
return head == null;
}
public override string ToString() {
if (this.isEmpty()) return "()";
string s = "";
Element tmp = this.head;
while (tmp != null) {
s += tmp.key + " ";
tmp = tmp.next;
}
return s;
}
}
class MainClass {
public static void Main (string[] args) {
LinkedListStack s = new LinkedListStack();
s.push("A");
s.push("B");
Console.WriteLine (s.isEmpty());
Console.WriteLine (s);
s.pop();
s.pop();
Console.WriteLine (s.isEmpty());
Console.WriteLine (s);
s.push("B");
s.push("A");
Console.WriteLine (s.isEmpty());
Console.WriteLine (s);
Console.WriteLine (s.peek());
}
}
EDIT: Drobna zmiana, nadpisane ToString
, zamiast printStack
.