Linked List using classes, inserting at tail in C++:
#include <iostream>
using namespace std;
class node{
public:
node();
void insert();
void print();
private:
//int index;
int value;
node *next;
node *head;
node *tail;
};
node::node(){
head = 0, tail = 0;
}
int main(){
node ll;
while (1){
cout << "1. Insert\n2. Print All "; int opt; cin >> opt;
switch(opt){
case 1:
ll.insert();
break;
case 2:
ll.print();
break;
}
}
return 0;
}
void node::insert(){
node *temp = new node;
cout << "Value: ";
cin >> temp->value;
temp -> next = 0;
//insert at tail.
if (head != NULL && tail != NULL){
tail->next = temp;
tail = temp;
}
else{
head = temp;
tail = temp;
}
}
void node::print(){
node *h = head;
while (h!= NULL){
cout << h->value << endl;
h = h->next;
}
}
#include <iostream>
using namespace std;
class node{
public:
node();
void insert();
void print();
private:
//int index;
int value;
node *next;
node *head;
node *tail;
};
node::node(){
head = 0, tail = 0;
}
int main(){
node ll;
while (1){
cout << "1. Insert\n2. Print All "; int opt; cin >> opt;
switch(opt){
case 1:
ll.insert();
break;
case 2:
ll.print();
break;
}
}
return 0;
}
void node::insert(){
node *temp = new node;
cout << "Value: ";
cin >> temp->value;
temp -> next = 0;
//insert at tail.
if (head != NULL && tail != NULL){
tail->next = temp;
tail = temp;
}
else{
head = temp;
tail = temp;
}
}
void node::print(){
node *h = head;
while (h!= NULL){
cout << h->value << endl;
h = h->next;
}
}
No comments:
Post a Comment