home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky comp.lang.c:12255 comp.programming:2292
- Path: sparky!uunet!cs.utexas.edu!asuvax!ncar!noao!amethyst!organpipe.uug.arizona.edu!news
- From: dave@cs.arizona.edu (Dave Schaumann)
- Newsgroups: comp.lang.c,comp.programming
- Subject: Re: A LITTLE BRAINTEASER...
- Message-ID: <1992Aug13.030019.195@organpipe.uug.arizona.edu>
- Date: 13 Aug 92 03:00:19 GMT
- References: <aet.713608023@munagin>
- Sender: news@organpipe.uug.arizona.edu
- Reply-To: dave@cs.arizona.edu (Dave Schaumann)
- Followup-To: comp.lang.c
- Organization: University of Arizona
- Lines: 58
- In-Reply-To: aet@mullian.ee.mu.OZ.AU (bert thompson)
-
- In article <aet.713608023@munagin>, aet@mullian (bert thompson) writes:
- >i have a small problem that's been bugging for a while now.
- >
- >here's a program that reverses input from the keyboard:
- >
- >main()
- > char ch = getchar();
- ^^^^
- Should be `int'
-
- > if (ch == EOF)
- > ;
- > else {
- > main();
- > putchar(ch);
- > }
- >}
- >
- >the interesting thing about the program is that it uses no data structures
- >(structs, arrays, pointers, etc..), to do its thing. everything is thrown
- >on the stack.
-
- But the stack /is/ a data structure! Just because push is defined as
- procedure call and pop is defined as procedure return doesn't make it
- any less of a data structure than if you had programmed an explicit
- stack.
-
- In fact, the I/O streams you are also relying on can be considered a
- queue. Using a stack as temporary storage, you can easily reverse
- any queue:
-
- queue_t queue ;
- stack_t stack ;
-
- ...
-
- stack.make_empty() ;
- while( !queue.empty() )
- stack.push( queue.get() ) ;
-
- while( !stack.empty() )
- queue.put( stack.pop() ) ;
-
- Writing this as a recursive subroutine (which uses an implicit stack), you get
-
- void reverse_queue( queue_t queue ) {
-
- data_t data ;
-
- if( !queue.empty() ) {
- data = queue.get() ;
- reverse_queue( queue ) ;
- queue.put( data ) ;
- }
- }
-
- --
- Dave Schaumann dave@cs.arizona.edu
-