Tiny brain teaser C code puzzle

Today’s post is a simple morning mystery function. What am I?
(beware spoilers in the comments)

typedef struct node {
  /* data struct */
  struct node *next;
} node;



node* mystery(node* first) {
  node * prev=NULL;
  node * temp=NULL;
  node * cur=first;

  while (cur != NULL) {
    temp = cur->next;
    cur->next = prev;
    prev = cur;
    cur = temp;
  }
  return prev;
}

Thanks for error catching from redditors.

*update*: GoldyOrNugget has a functional programming python example which you can work through.

def magic_function(*fs):
  return lambda x: reduce(lambda a,b: b(a), (fs+x)[::-1])
Categories: Uncategorized
Tags: ,
  • Mystery Poster

    I am node* reverse(node* first).

  • Bijo

    list reverse

  • http://twitter.com/thomas_luce Thomas Luce

    List reverse. If you wanted to be really clever you could get rid of the need for a temp variable by xoring the parts you want to switch around with each other twice.

  • http://www.victusspiritus.com/ Mark Essel

    Fancy :) .

  • Anonymous

    A reverse sort.

  • kst

    For certain values of “fancy”. The “^” operator doesn’t apply to pointers, only to integers, and conversion between pointers and integers is implementation-defined. It’s entirely possible, on some systems, that you could generate an invalid intermediate value that could cause your program to crash — or that you could just quietly generate bad results.

    Even if the xor trick works, it’s one more thing you have to consider as a possible cause of that mysterious sporadic bug that shows up six months later.

    Just use the temporary.

  • Anonymous

    I’d like code up more puzzles, varying complexity, and hint levels. This may have been a little too easy for a first go. But I was acquisitive even non coding types could acumen their way through it. The pointers present an issue to that group though.