Help with stacks please

L

LedZep

This program has to use a stack to determine whether a
string is a palindrome (a string that is spelled identically backward
and forward). The program has to ignore spaces, case sensitivity and
punctuation. I have to somehow take the input from the txtbox, stack
it letter by letter onto a stack, then display it written forward and
below it written backwards. I understand the concept of stacks -- I
just need a little push in the right direction.


Here's my code. Two questions: 1.) Why doesnt the enumerator display
the the item(s) pushed onto the stack in txtOutput??? When I have a
separate button to push an item onto a stack
(stack.Push(txtInput.Text))and then another button to display the
stack:

While enumerator.MoveNext()
buffer.Append(enumerator.Current)
txtOutput.Text = buffer.ToString
End While

it works fine. Why cant I do both push and display in the same button?

2.) Any suggestions on how to push "word" onto the stack letter by
letter? I tried using a loop where

count = word.Length

Do while i =< count
stack.Push(word.Chars(n))
n = n + 1
i = i + 1
Loop


This kinda works because it displays the stack LIFO-esque (the word
appears backwards when displayed). So then how would I display "word"
in non-LIFO (so that "word" appears correctly spelled)? Is Chars the
right way to enter "word" letter by letter? Should I make it an
array??? Kinda confused....

Dim stack As New stack()
Dim word As String

Private Sub cmdDisplay_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdDisplay.Click
Dim enumerator As IEnumerator = stack.GetEnumerator
Dim buffer As StringBuilder = New StringBuilder()
Dim count As Integer
word = txtInput.Text
count = word.Length
stack.Push(word)

While enumerator.MoveNext()
buffer.Append(enumerator.Current)
txtOutput.Text = buffer.ToString
End While

End Sub

Any help is MUCH APPRECIATED,

LedZep
 
R

Russell Jones

Since you want to display the word first forward, then backward, why don't
you display it once as you push the letters onto the stack, and again as you
pull them off. Then you can do it in one routine easily. This also shows you
how to push the letters onto the stack one at a time:

Private Sub cmdDisplay_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdDisplay.Click
Dim st As New Stack
Dim count As Integer
Dim word As String
word = txtInput.Text
txtOutput.Clear()
For i As Integer = 0 To word.Length - 1
txtOutput.AppendText(word.Chars(i))
st.Push(word.Chars(i))
Next
Dim enumerator As IEnumerator = st.GetEnumerator
While enumerator.MoveNext()
txtOutput.AppendText(enumerator.Current.ToString)
End While

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top