1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
#include <iostream>
struct Node
{
int data;
Node* next;
Node( int d, Node* n = nullptr )
: data( d ), next( n ) { }
};
// Remove curr from the list.
// precond: neither head, tail nor curr are null.
// prev points to curr or is null if curr is head.
void remove( Node*& head, Node*& tail, Node* curr, Node* prev )
{
Node* next = curr->next;
if( prev )
prev->next = next;
else
head = next;
delete curr;
curr = next;
if( !curr )
tail = prev;
}
void print( Node* nd )
{
for ( ; nd; nd = nd->next)
std::cout << nd->data << ' ';
std::cout << '\n';
}
int main()
{
Node *head = nullptr, *tail = nullptr;
for( int n: { 1, 2, 3, 4, 5, 6, 7, 8 })
{
// prepend
//head = new Node( n, head );
//if( !tail ) tail = head;
// append
Node* nd = new Node( n );
if( tail )
tail->next = nd;
else
head = nd;
tail = nd;
}
// Start curr at head...
Node *curr = head, *prev = nullptr;
// ... and advance n positions.
int n = 3;
for( int i = 0; curr && i < n; ++i )
{
prev = curr;
curr = curr->next;
}
print( head );
std::cout << "tail: " << (tail ? tail->data : -1) << '\n';
if( curr )
remove( head, tail, curr, prev );
print( head );
std::cout << "tail: " << (tail ? tail->data : -1) << '\n';
}
|