Reverse a linked list.
- static void Reverse(struct node** headRef)
- {
- struct node* target = NULL;
- struct node* current = *headRef;
- struct node* next;
- while (current)
- {
- next = current->next; // tricky: save the next node
- current->next = target;
- target = current;
- current = next;
- }
- *headRef = target;
- }
- // new head in headRef
- // return the end node
- struct node* recursiveReverse(struct node** headRef)
- {
- struct node *current = *headRef;
- struct node *ret = NULL;
- if (current)
- {
- if (current->next)
- {
- struct node *tail = recursiveReverse(¤t->next);
- tail->next = current;
- *headRef = current->next;
- current->next = NULL;
- }
- ret = current;
- }
- return ret;
- }
Dynamic two dimension array
Using int as an example
- int **malloc2D(int m, int n)
- {
- int **p = (int **)malloc(m * sizeof(int *));
- for (int i = 0; i < m; i++)
- {
- p[i] = (int *)malloc(n * sizeof(int));
- }
- return p;
- }
- void free2D(int **p, int m)
- {
- for (int i = 0; i < m; i++)
- {
- free(p[i]);
- }
- free(p);
- }
Function with a variable number of arguments
- // Printf to a char buffer and return the pointer.
- char *formatString(char *dstStr, const char *fmt, ...)
- {
- va_list argp;
- va_start(argp, fmt);
- vsprintf(dstStr, fmt, argp);
- va_end(argp);
- return dstStr;
- }