home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky comp.lang.c:12316 comp.programming:2309
- Newsgroups: comp.lang.c,comp.programming
- Path: sparky!uunet!usc!sdd.hp.com!caen!destroyer!ubc-cs!alberta!cpsc.ucalgary.ca!jade!west
- From: west@jade.ab.ca (Darrin West)
- Subject: Re: A LITTLE BRAINTEASER...
- Message-ID: <1992Aug13.141021.16870@jade.ab.ca>
- Organization: Jade Simulations International, Inc.
- References: <aet.713608023@munagin>
- Date: Thu, 13 Aug 1992 14:10:21 GMT
- Lines: 76
-
- This solution does use a struct and a linked list (so I guess it HAS
- data structures), but it has the advantage (:-) of using only one
- function and no loops, and certainly does not use the heap.
-
- #include <stdio.h>
- struct X {
- char ch;
- struct X *last;
- };
-
- /* this program only works if called with no arguments */
- main(argc)
- struct X *argc;
- {
- struct X x;
-
- x.ch=getchar();
- x.last=argc;
-
- if (x.ch == EOF){
- /* we are now in the printing phase */
- if (argc != (struct X*)1) {
- /* we are in the middle of a line */
- main(argc->last); /* print the first of the line */
- putchar(argc->ch); /* and then print this letter */
- }
- /* we reached the front of the line */
- }
- else{
- /* we are in the reading phase */
- if (x.ch == '\n') main(1); /* keep reading; mark the end of the line */
-
- /* this is the neat part, in most cases this reads the rest of the
- line but when the previous statement was executed (we are at the end
- of a line) this prints the current line. */
- main(&x);
- }
- }
-
- I had considered not using a struct, but just two variables juxtaposed on
- the stack and doing some pointer incrementing, but that isn't portable :-).
- (maybe if I did this: int *last1;char ch;int *last2; and set both last
- pointers, it would work on inverted stack machines too.)
-
- Ok, I tried it (looks even better, and might even port! :-)
-
- #include <stdio.h>
-
- main(argc)
- int *argc;
- {
- int *last1;
- int ch;
- int *last2;
-
- ch = getchar();
- last1 = last2 = argc;
-
- if (ch == EOF){
- if (argc != (int*)1) {
- main(*(argc+1));
- putchar(*argc);
- }
- }
- else{
- if (ch == '\n') main(1);
- main(&ch);
- }
- }
-
-
- Anyone for a grosser solution?
-
- --
- Darrin West, MSc.
- Jade Simulations International Corporation. west@jade.ab.ca
-