This article explains the concept of singly link list data structure and provides the simple implementation
in C++.
//// Created by Laxmi Kadariya on 7/15/17.//
#include <iostream>using namespace std;
class node{
private:
int value;
node* next;
public:
node(){
}
void set_value(int value_arg){
value = value_arg;
}
void set_next(node* next_arg)
{
next = next_arg;
}
int show_value(){
return value;
}
node* show_next()
{
return next;
}
};
class linklist{
private:
node* head;
public:
linklist(){
head = NULL;
}
void add_node(int value);
void display_node();
int length_list();
void del( int value);
};
void linklist::add_node(int value) {
node *Node = new node();
Node->set_value(value);
Node->set_next(NULL);
node* tmp = head;
if(tmp == NULL)
{
head = Node;
}
else {
while(tmp->show_next() != NULL)
{
tmp = tmp->show_next();
}
tmp->set_next(Node);
}
cout<<"node"<<value<< "added"<<endl;
}
int linklist::length_list() {
int len = 0;
node* tmp = head;
while(tmp->show_next() != NULL){
tmp = tmp->show_next();
len = len+1;
}
return len+1;
}
void linklist::del(int value) {
node* tmp = head;
node* prev;
while(tmp->show_next() != NULL)
{
if(tmp->show_value() == value)
{
if(head->show_value() == tmp->show_value())
{
head = head->show_next();
}
else{
prev->set_next(tmp->show_next());
}
delete tmp;
break;
}
else{
prev=tmp;
tmp = tmp->show_next();
}
}
if(tmp->show_next() == NULL and tmp->show_value() == value)
{
if(head->show_next() == NULL and head->show_value() == value)
{
head = NULL;
delete tmp;
}
else {
prev->set_next(tmp->show_next());
delete tmp;
}
}
}
void linklist::display_node() {
node* tmp = head;
while(tmp->show_next() != NULL)
{
std::cout << tmp->show_value()<<endl;
tmp = tmp->show_next();
}
std::cout << tmp->show_value()<<endl;
}
int main(){
linklist list;
list.add_node(10);
list.add_node(20);
list.add_node(30);
list.add_node(40);
list.add_node(50);
list.display_node();
int size = list.length_list();
cout<<size<<endl;
list.del(30);
list.display_node();
size = list.length_list();
cout<<size<<endl;
}
No comments:
Post a Comment