gianluca.sclano
BAN USERmy C/C++ solution
#include <iostream>
/*
given a LinkedList like 1->2->3->4->5->6
Modify it as :
1->6->2->5->3->4
*/
struct linkednode {
int val;
linkednode *next;
};
int main()
{
//build -----------------------------------------------------------------
linkednode* root = new linkednode();
root->val = -1;
root->next = NULL;
linkednode* succ = NULL;
linkednode* last = NULL;
linkednode* base = root;
for (int i = 1; i <= 6; i++)
{
succ = new linkednode();
succ->val = i;
succ->next = NULL;
base->next = succ;
base = succ;
}
last = succ;
// printout -----------------------------------------------------------------
base = root->next;
printf(" initial ---------\n");
while (base != NULL)
{
printf("%d\n", base->val);
base = base->next;
}
// reverse -----------------------------------------------------------------
base = root->next;
linkednode* candidate = last;
linkednode* precandidate = NULL;
while (base->next != NULL && base->next != precandidate)
{
// find the previous before the latest candidate
linkednode* appcursor = root->next;
while (appcursor->next != NULL)
{
precandidate = appcursor;
appcursor = appcursor->next;
}
//make the substitution
appcursor = base->next;
candidate->next = base->next;
base->next = candidate;
precandidate->next = NULL;
candidate = precandidate;
base = appcursor;
}
// printout again -----------------------------------------------------------------
printf(" reversed ---------\n");
base = root->next;
while (base != NULL)
{
printf("%d\n", base->val);
base = base->next;
}
system("PAUSE");
return 1;
}
My C/C++ solution
- gianluca.sclano September 01, 2016