Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
alternate list
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
// 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); }
g++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.32 sec, absolute running time: 0.04 sec, cpu time: 0 sec, memory peak: 3 Mb, absolute service time: 0.36 sec
fork mode
|
history
|
discussion