Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
alternate list
// 1. Given linked list as a-x-b-y-c-z // output it as a-b-c-z-y-x // that is reverse alternate element and append to end of list #include <iostream> using namespace std; struct Node { int data; Node* next; Node(int d, Node* n): data(d), next(n) {} }; Node* reverse(Node* node) { Node* prev = NULL; Node* cur = node; Node* next; while (cur) { next = cur->next; cur->next = prev; prev = cur; cur = next; } return prev; } void alternate(Node* node) { Node* cur = node; Node* second = cur->next; Node* before; bool b = true; while (cur) { if (b) before = cur; b = !b; Node* firstNext = cur->next; Node* secondNext = NULL; if (firstNext) secondNext = firstNext->next; cur->next = secondNext; cur = firstNext; } before->next = reverse(second); } void print(Node* n) { while (n) { cout << n->data << " "; n = n->next; } cout << endl; } int main() { Node* node = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, new Node(6, new Node(7, NULL))))))); print(node); alternate(node); print(node); }
run
|
edit
|
history
|
help
0
good triplet
cppPyFoodVatTip
MovConstrAssign2
no_error
bin search
completeBubbleSort
DailyGroceryHisto
runtime template mode processor
Counting top students
Simple use of function templete and namespace