Last active
April 25, 2024 09:11
-
-
Save charlierm/5691020 to your computer and use it in GitHub Desktop.
Linked list written in c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdlib> | |
class Node | |
{ | |
public: | |
Node* next; | |
int data; | |
}; | |
using namespace std; | |
class LinkedList | |
{ | |
public: | |
int length; | |
Node* head; | |
LinkedList(); | |
~LinkedList(); | |
void add(int data); | |
void print(); | |
}; | |
LinkedList::LinkedList(){ | |
this->length = 0; | |
this->head = NULL; | |
} | |
LinkedList::~LinkedList(){ | |
std::cout << "LIST DELETED"; | |
} | |
void LinkedList::add(int data){ | |
Node* node = new Node(); | |
node->data = data; | |
node->next = this->head; | |
this->head = node; | |
this->length++; | |
} | |
void LinkedList::print(){ | |
Node* head = this->head; | |
int i = 1; | |
while(head){ | |
std::cout << i << ": " << head->data << std::endl; | |
head = head->next; | |
i++; | |
} | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
LinkedList* list = new LinkedList(); | |
for (int i = 0; i < 100; ++i) | |
{ | |
list->add(rand() % 100); | |
} | |
list->print(); | |
std::cout << "List Length: " << list->length << std::endl; | |
delete list; | |
return 0; | |
} |
Can anyone explain me, if we create LinkedtList object then head (wiyh the help of default contructor ) will become null and data will be lost.
/*
I am getting error : In member function 'void linkedlist::add(std::string&)':
error: 'h' was not declared in this scope
can anyone explain me why i am getting this error message
*/
#include
#include
using namespace std;
//making class node
class node{
public:
friend class linkedlist;
node(){
data = "0";
next = NULL;
}
string data;
node* next;
};
//making class to linkedlist
class linkedlist{
public:
linkedlist(){
node* h = NULL;
}
//function to add data node in existing linked list
void add(string& str){
node* newnode = new node;
newnode->data = str;
if(h !=NULL){
h->next = newnode;
}
else{
newnode->next = h->next;
h->newnode;
}
}
};
int main()
{
linkedlist l1;
string name;
//loop to enter data from user
while(true){
cout<<"type \"q\" to exit or type name you want to add: ";
cin>> name;
if(name!="q"){
l1.add(name);
}
else break;
}
return 0;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how do you create another list different from the already created using the same class