I want to actually reverse a single linked list without using many
variables, i have a recurssive solution, but i wanted an iterative
one. can anyone help me on this?
/* ======================================================= */
/* believed necessary and sufficient for NULL terminations */
/* Reverse a singly linked list. Reentrant (pure) code */
nodeptr revlist(nodeptr root)
{
nodeptr curr, nxt;
if (root) { /* non-empty list */
curr = root->next;
root->next = NULL; /* terminate new list */
while (curr) {
nxt = curr->next; /* save for walk */
curr->next = root; /* relink */
root = curr; /* save for next relink */
curr = nxt; /* walk onward */
}
}
/* else empty list is its own reverse; */
return root;
} /* revlist */
which requires that a 'nodeptr' be defined to point to a struct
with at least a next field, of type nodeptr. Usage is of the form:
nodeptr root;
....
/* code to form the list */
...
root = revlist(root)