Hacker News new | ask | show | jobs
by xfs 3134 days ago
> 7. Build — Local References

    struct node* BuildWithLocalRef() {
      struct node* head = NULL;
      struct node** lastPtrRef= &head; // Start out pointing to the head pointer
      int i;
      for (i=1; i<6; i++) {
        Push(lastPtrRef, i); // Add node at the last pointer in the list
        lastPtrRef= &((*lastPtrRef)->next); // Advance to point to the new last pointer
      }
      // head == {1, 2, 3, 4, 5};
      return(head);
    }
> This technique is short, but the inside of the loop is scary. This technique is rarely used, but it's a good way to see if you really understand pointers.

> This technique is never required to solve a linked list problem, but it will be one of the alternative solutions presented for some of the advanced problems. The code is shorter this way, but the performance is probably not any better.

This is what Linus Torvalds called "good taste" code and used in Linux kernel. There was some argument about it though: https://news.ycombinator.com/item?id=5030845.

(Incidentally, I found Nginx is written in the same style recently as I read it - manual linked list manipulation with this double pointer technique everywhere..)