Wednesday, May 11, 2011

Here are three reverse methods I came up with

Three methods:
1) simple iteration
void iterative_reverse()
{
Node p, q, r;

if(head == NULL)
return;

p = head;
q = p.next;

p.next = NULL;

while (q != NULL)
{
r = q.next;
q.next = p;
p = q;
q = r;
}

head = p;
}

2) Using a stack data structure
void iterative_reverse_2()
{
Stack s = new Stack();
Node cur, prev;
for (cur = head; cur != NULL; cur=cur.next)
{
s.push(cur);
}
head = s.pop();
cur = head;
while (! s.empty())
{
prev = cur;
cur = s.pop();
prev.next = cur;
}
cur.next = NULL;
tail = cur;
}

3) using the call stack
void reverse()
{
reverse2(NULL, head);
Node temp = head;
head = tail;
tail = temp;
}

void reverse2(Node prev, Node current)
{
if (current == NULL)
return;
reverse(current, current.next);
current.next = prev;
}

No comments:

Post a Comment