#include <iostream>
usingnamespace std;
class Node
{
public:
int value;
Node * next;
Node();
Node(int);
};
Node::Node():value(0),next(NULL){}
Node::Node(int v):value(v),next(NULL){}
void Print(Node* h)
{
while(h)
{
cout<<" -> "<<h->value;
h=h->next;
}
cout<<endl;
}
void Create(Node*& head, int n)
{
head = new Node(1);
Node * tmp=head;
for(int i=2; i<=n; i++)
{
tmp->next = new Node(i);
tmp = tmp->next;
}
}
void AddHead(Node*& head, int n)
{
Node * tmp = new Node(n);
tmp->next = head;
head=tmp;
}
void AddTail(Node*& head, int n)
{
Node* tmp = new Node(n);
if(!head)
{
head=tmp;
return;
}
Node * t=head;
while(t->next) t=t->next;
t->next=tmp;
}
void DeleteHead(Node*& head)
{
if(!head) return;
Node* tmp = head;
head = head->next;
delete tmp;
}
int main()
{
Node * h = NULL; //this is the head of the list
cout<<"first manually create 3 nodes and link them together\n";
Node* one = new Node(1);
Node* two = new Node(2);
Node* three = new Node(3);
h=one;
one->next=two;
two->next=three;
Print(h);
cout<<"now call Create() function to create 8 nodes\n";
Create(h, 8);
Print(h);
cout<<"adding a node with value 44 at the head of existing list\n";
AddHead(h, 44);
Print(h);
cout<<"adding a node with value 55 at the tail of existing list\n";
AddTail(h, 55);
Print(h);
cout<<"deleting head\n";
DeleteHead(h);
Print(h);
return 0;
}
#include <iostream>
struct Node
{
int value;
Node* next;
/*explicit*/ Node( int v = 0, Node* nxt = nullptr ) : value(v), next(nxt) {}
};
std::size_t length( const Node* head )
{
std::size_t n = 0 ;
for( const Node* current = head ; current != nullptr ; current = current->next ) ++n ;
return n ;
}
Node* delete_tail( Node*& head )
{
if( head == nullptr ) returnnullptr ;
elseif( head->next == nullptr ) { delete head ; head = nullptr ; } // delete the only element
else // at least two elements
{
// get to the node just before the last node
Node* prev = head ;
for( Node* current = head->next ; current->next != nullptr ; current = current->next ) prev = current ;
delete prev->next ; // delete the last element
prev->next = nullptr ;
}
return head ;
}
int main()
{
Node* list = new Node( 23, new Node( 35, new Node( 12, new Node( 48, new Node( 28, new Node( 90, new Node(73) )))))) ;
while( list != nullptr )
{
for( Node* current = list ; current != nullptr ; current = current->next )
std::cout << current->value << " --> " ;
std::cout << "nullptr (length:" << length(list) << ")\n" ;
delete_tail(list) ;
}
}