jnguyenjr
BAN USERpublic void ReversePairs(Node list)
{
if(list == null)
{
return;
}
Node first = list;
Node second = list.next;
Node previous = null;
while(first != null && second != null)
{
// swap pointers
first.next = second.next;
second.next = first;
// if previous exists, then assign to the second node since it's before first now
if(previous != null)
{
previous.next = second;
}
// set previous to what is now the second node
// that way if we need to process more, we can point to the new firsts
previous = first;
// move to the next pair. If first is null, then there's nothing else to do
// if first's next is null, we still assign but while loop won't be true, so it will break
first = first.next;
if(first == null)
{
break;
}
second = first.next;
}
}
My idea is do traverse the tree as you normally would. If we find the node that we are at the same node as the node calling next, then any node to the right of me is a possibility as my next, since we are traversing from left to right (if they are at the same depth). If we ever have the depth as the same as the desired depth, then set the result (if it hasn't been set yet). Any subtrees below our "next" and to the right wont be processed since we return out if we have result.
- jnguyenjr May 26, 2015