Create graph using adjacency list - c++

#include<iostream>
using namespace std;
class TCSGraph{
public:
void addVertex(int vertex);
void display();
TCSGraph(){
head = NULL;
}
~TCSGraph();
private:
struct ListNode
{
string name;
struct ListNode *next;
};
ListNode *head;
}
void TCSGraph::addVertex(int vertex){
ListNode *newNode;
ListNode *nodePtr;
string vName;
for(int i = 0; i < vertex ; i++ ){
cout << "what is the name of the vertex"<< endl;
cin >> vName;
newNode = new ListNode;
newNode->name = vName;
if (!head)
head = newNode;
else
nodePtr = head;
while(nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
}
}
void TCSGraph::display(){
ListNode *nodePtr;
nodePtr = head;
while(nodePtr){
cout << nodePtr->name<< endl;
nodePtr = nodePtr->next;
}
}
int main(){
int vertex;
cout << " how many vertex u wan to add" << endl;
cin >> vertex;
TCSGraph g;
g.addVertex(vertex);
g.display();
return 0;
}

There is a problem in you addvertex method:
You have:
if (!head)
head = newNode;
else
nodePtr = head;
while(nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
but it should be:
if (!head) // check if the list is empty.
head = newNode;// if yes..make the new node the first node.
else { // list exits.
nodePtr = head;
while(nodePtr->next) // keep moving till the end of the list.
nodePtr = nodePtr->next;
nodePtr->next = newNode; // add new node to the end.
}
Also you are not making the next field of the newNode NULL:
newNode = new ListNode;
newNode->name = vName;
newNode->next= NULL; // add this.
Also its a good practice to free up the dynamically allocated memory. So instead of having an empty destructor
~TCSGraph();
you can free up the list in the dtor.
EDIT: More bugs
You have a missing ; after the class declaration:
class TCSGraph{
......
}; // <--- add this ;
Also your destructor is only declared. There is no def. If you don't want to give any def, you must at least have a empty body. So replace
~TCSGraph();
with
~TCSGraph(){}

Have you taken a look at Boost Graph Library and boost::adjacency_list?

Related

Tried appending multiple nodes in LinkedList c++ but it's just printing 1 node

I tried appending multiple nodes in LinkedList c++ but it is just printing 1 node as I run it. Kindly review it, and help me fix it.
#include <iostream>
using namespace std;
//here is the node
struct Node {
int data;
struct Node* next;
};
// ------------here is linkedlist-----------
class LinkedList {
private:
Node* head;
public:
LinkedList()
{
head = NULL;
}
//----------- append function ------------
void appendNode(int d)
{
Node* newNode = new Node;
Node* nodePtr;
newNode->data = d;
newNode->next = NULL;
if (!head)
{
head = newNode;
}
else
{
nodePtr = head;
while (nodePtr->next)
{
nodePtr = nodePtr->next;
nodePtr->next = newNode;
}
}
}
//--------------- display function--------------
void display()
{
Node* nodePtr;
nodePtr = head;
while (nodePtr != NULL)
{
cout << nodePtr->data << endl;
nodePtr = nodePtr->next;
}
}
};
//-------------- main function -------------
int main()
{
LinkedList ll;
ll.appendNode(2);
ll.appendNode(21);
ll.appendNode(11);
ll.display();
}
Change your while loop from:
while (nodePtr->next)
{
nodePtr = nodePtr->next;
nodePtr->next = newNode;
...
}
to
while (nodePtr->next)
{
nodePtr = nodePtr->next;
...
}
nodePtr->next = newNode;
Also, in C++ use nullptr instead of NULL.

How do I make my Linked List Print backwards in C++

How do I make my program print the Linked List backwards? I got the printForward function working fine but the printBackwards function just doesn't seem to do anything. I think I'm on the right track but I'm a little stuck right now. I think the while loop isn't running because temp is NULL for some reason.
Any help would be great.
Thanks
List.h
#include <iostream>
using namespace std;
class LinkedList
{
private:
struct Node
{
int data;
Node * next;
Node * prev;
};
Node * head, *tail;
public:
LinkedList();
bool addAtBeginning(int val);
bool remove(int val);
void printForward() const;
void printBackward() const;
};
#endif
List.cpp
#include "List.h"
LinkedList::LinkedList()
{
head = NULL;
tail = NULL;
}
bool LinkedList::addAtBeginning(int val)
{
Node* temp;
temp = new Node;
temp->data = val;
temp->next = head;
head = temp;
return false;
}
bool LinkedList::remove(int val)
{
return false;
}
void LinkedList::printForward() const
{
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
void LinkedList::printBackward() const
{
Node* temp = tail;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->prev;
}
cout << endl;
}
app.cpp
#include "list.h"
int main()
{
LinkedList aList;
aList.addAtBeginning(3);
aList.addAtBeginning(10);
aList.addAtBeginning(1);
aList.addAtBeginning(7);
aList.addAtBeginning(9);
aList.addAtBeginning(12);
aList.printForward();
aList.printBackward();
system("pause");
return 0;
}
I find it a bit odd that you only have an addAtBeginning method, and no method to add at the end, the latter which I would consider to be normal use of a linked list. That being said, I think the immediate problem here is that you never assign the tail to anything. Try this version of addAtBeginning:
bool LinkedList::addAtBeginning(int val)
{
Node* temp;
temp = new Node;
temp->data = val;
temp->next = head;
if (head != NULL)
{
head->prev = temp;
}
if (head == NULL)
{
tail = temp;
}
head = temp;
return false;
`}
The logic here is that for the first addition to an empty list, we assign the head and tail to the initial node. Then, in subsequent additions, we add a new element to the head of the list, and then assign both the next and prev pointers, to link the new node in both directions. This should allow you to iterate the list backwards, starting with the tail.
Update addAtBeginning function with given:
bool LinkedList::addAtBeginning(int val)
{
Node* temp;
temp = new Node;
temp->data = val;
temp->prev = temp->next = NULL;
// If adding first node, then head is NULL.
// Then, set Head and Tail to this new added node
if(head == NULL){
// If this linked list is circular
temp->next = temp->prev = temp;
head = tail = temp;
}else{ // If we already have at least one node in the list
// If this linked list is circular
temp->prev = head->prev;
temp->next = head;
head->prev = temp;
head = temp;
}
return false;
}
But remember, if you copy this function with the parts that it makes this list circular, you will get an infinite loop. So, either change print function or dont copy that parts.

Doubly linked list seg faults

I am trying to display a doubly linked list backwards, but every time I try to run anything even remotely touching the "prev" pointer in the program I get a seg fault.
I've been trying to figure this out for about 4 hours now and I just can't seem to pin it down. I can't tell if the issue is coming from my print backwards function or from the actual prev pointers themselves.
#include <iostream>
#include "list.h"
LinkedList::LinkedList(){
head = NULL;
tail = NULL;
};
bool LinkedList::addAtBeginning(int val){
Node *upd8L = head; // This Node will update Last
Node *upd8 = head;; // This Node will update the previous pointers
Node *point = new Node(); // This Node will insert the new node at the beginning
point->data=val; // This sets the data in the new node
point->next=head; // This sets the next pointer to the same as head
head = point; // This sets the head to the new Node
while(upd8){
upd8 = upd8->next;
upd8->prev = upd8L;
upd8L=upd8L->next;
}
return true;
};
bool LinkedList::remove(int val){
Node *temp = head;
Node *trail = 0;
while(temp != NULL){
if(temp->data == val){
if(temp->next == head->next){
head = head->next;
}else{
trail->next = temp->next;
}
delete temp;
}
trail = temp;
temp = temp->next;
}
return true;
};
void LinkedList::printForward() const{
Node *temp;
temp = head;
while(temp){
cout << temp -> data << endl;
temp = temp->next;
}
};
void LinkedList::printBackward() const{
Node *temp = head;
while(temp){
temp = temp->next;
cout << temp->data << endl;
}
while(temp){
cout << temp->data;
cout << "Pop" << endl;
temp = temp-> prev;
}
};
If possible, I'd love an explanation as to what is bugging up my program rather than just a straight answer, I want to know what I'm doing wrong and why it's wrong.
Thank you!
edit
Here's list.h
#ifndef LIST_H
#define LIST_H
#include <iostream>
using namespace std;
class LinkedList
{
private:
struct Node
{
int data;
Node * next;
Node * prev;
};
Node * head, * tail;
public:
LinkedList();
bool addAtBeginning(int val);
bool remove(int val);
void printForward() const;
void printBackward() const;
};
#endif
The function printBackward() may cause a seg-fault in the last iteration of the loop. while(temp) means iterate till you get the element out of the list NULL. Then you assigning temp = temp->next where temp->next is NULL. Now when you are calling cout << temp->data << endl; you are trying to get data from NULL pointer. Try to change the order. First display the node data, then change the temp pointer. An example:
void LinkedList::printBackward() const{
Node *temp = head;
while(temp){
cout << temp->data << endl;
temp = temp->next;
}
What you are doing wrong is getting the data from a NULL pointer.
So, I figured it out after a ton of trial and error!
The biggest issue I was having that kept giving me segmentation errors was whenever I was removing elements of the list I was failing to update the "prev" part of the node, and as a result any time I tried to read the list backwards I was getting a seg error.
//put your implementation of LinkedList class here
#include <iostream>
#include "list.h"
LinkedList::LinkedList(){
head = NULL;
tail = NULL;
};
bool LinkedList::addAtBeginning(int val){
Node *point = new Node(); // This Node will insert the new node at the beginning
point->data=val; // This sets the data in the new node
point->next=head; // This sets the next pointer to the same as head
head = point; // This sets the head to the new Node
if(head->next != NULL){
Node *temp = head->next;
temp->prev = head;
}
return true;
};
bool LinkedList::remove(int val){
Node *temp = head->next;
Node *trail = head;
if(head->data ==val){
head = head->next;
head->prev = NULL;
delete trail;
}else{
while(temp != NULL){
if(temp->data == val){
if(temp->next != NULL){
trail->next = temp->next;
delete temp;
temp= temp->next;
temp->prev=trail;
}else{delete temp;
trail->next = NULL;
}
}
trail = temp;
temp = temp->next;
}
}
return true;
};
void LinkedList::printForward() const{
Node *temp;
temp = head;
while(temp){
cout << temp->data << endl;
temp = temp->next;
}
};
void LinkedList::printBackward() const{
Node *temp = head;
while(temp->next != NULL){
temp = temp->next;
}
while(temp->prev != NULL){
cout << temp->data << endl;
temp = temp->prev;
}
cout << head->data << endl;
};

I'm having trouble displaying a linked list

When I run my program, it works as intended, except the items in the list have no spaces between them when the displayList() function is called. I have 3 files. The main cpp file is ShoppingList.cpp. Then I have two other files for the linked list classification and implementation.
//ShoppingList.cpp
//Michael Hery
//COP 2001
//11/9/17
//Shopping List
#include <iostream>
#include <string>
#include "strList.h"
#include "strlist.cpp"
using namespace std;
int main()
{
//Define a NumberList object
StrList list;
string item;
string delItem;
int menuSelection;
//Ask the user how many items to
//put in the list
cout << "How many items would you like to put it the list? >> ";
cin >> menuSelection;
while (menuSelection < 1)
{
cout << "Please enter a valid number (greater than 0) >> ";
cin >> menuSelection;
}
for (int i = 0; i < menuSelection; i++)
{
cout << "Please enter item " << i + 1 << ": ";
cin >> item;
list.appendNode(item);
}
list.displayList();
cout << "Which item do you wish to delete from the list? >> ";
cin >> delItem;
while (delItem == "")
{
cout << "Please enter a valid item >> ";
cin >> delItem;
}
list.deleteNode(delItem);
list.displayList();
//Wait for user input to exit program
system("PAUSE");
return 0;
}
//strList.h
#ifndef STRLIST_H
#define STRLIST_H
#include <iostream>
#include <string>
namespace
{
class StrList
{
private:
struct ListNode
{
std::string value;
struct ListNode *next;
};
ListNode *head;
public:
//Constructor
StrList()
{
head = nullptr;
}
//Destructor
~StrList();
//Linked List Operations
void appendNode(std::string item);
void insertNode(std::string item);
void deleteNode(std::string item);
void displayList() const;
};
}
#endif
//strList.cpp
#ifndef STRLIST_CPP
#define STRLIST_CPP
#include <iostream>
#include <string>
#include "strList.h"
void StrList::appendNode(std::string item)
{
ListNode *newNode;
ListNode *nodePtr;
//Allocate a new node and store item there
newNode = new ListNode;
newNode->value = item;
newNode->next = nullptr;
//If there are no nodes in the list
//make newNode the first node
if (!head)
head = newNode;
else //Otherwise, insert newNode at the end
{
//Initialize nodePtr to head of the list
nodePtr = head;
//Find the last node in the list
while (nodePtr->next)
nodePtr = nodePtr->next;
//Insert newNode as the last node
nodePtr->next = newNode;
}
}
void StrList::insertNode(std::string item)
{
ListNode *newNode;
ListNode *nodePtr;
ListNode *previousNode = nullptr;
//Allocate a new node and store num there
newNode = new ListNode;
newNode->value = item;
//If there are no nodes in the list
//make newNode the first node
if (!head)
{
head = newNode;
newNode->next = nullptr;
}
else //Otherwise, insert newNode
{
//Position nodePtr at the head of list
nodePtr = head;
//Initialize previousNode to nullPtr
previousNode = nullptr;
//Skip all nodes whose values is less than num
while (nodePtr != nullptr && nodePtr->value < item)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
//If the new node is to be the 1st in the list,
//insert it before all the other nodes
if (previousNode == nullptr)
{
head = newNode;
newNode->next = nodePtr;
}
else //Otherwise insert after the previous node
{
previousNode->next = newNode;
newNode->next = nodePtr;
}
}
}
void StrList::deleteNode(std::string item)
{
ListNode *nodePtr; //To traverse the list
ListNode *previousNode = nullptr; //To point to the previous node
//If the list is empty, do nothing
if (!head)
return;
//Determine if the first node is the one
if (head->value == item)
{
nodePtr = head->next;
delete head;
head = nodePtr;
}
else
{
//Initialize nodePtr to head of list
nodePtr = head;
//Skip all nodes whose value member is
//not equal to num
while (nodePtr != nullptr && nodePtr->value != item)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
//If nodePtr is not at the end of the list,
//link the previous node to the node after
//nodePtr, then delete nodePtr
if (nodePtr)
{
previousNode->next = nodePtr->next;
delete nodePtr;
}
}
}
StrList::~StrList()
{
ListNode *nodePtr; //To traverse the list
ListNode *nextNode; //To point to the next node
//Position nodePtr at the head of the list
nodePtr = head;
//While nodePtr is not at the end of the list
while (nodePtr != nullptr)
{
//Save a pointer to the next node
nextNode = nodePtr->next;
//Delete the current node
delete nodePtr;
//Position nodePtr at the next node
nodePtr = nextNode;
}
}
void StrList::displayList() const
{
ListNode *display;
display = head;
std::cout << "**********************************" << std::endl;
std::cout << "**** Your Shopping List ****" << std::endl;
std::cout << "**********************************" << std::endl;
while (display)
{
std::cout << display->value;
display = display->next;
}
}
#endif
The problem lies in the displayList(); function towards the end of the file.
Add a separator for between your values.
char const* sep = "";
while (display)
{
std::cout << sep << display->value;
sep = " ";
display = display->next;
}

Simple linked list in C++

I am about to create a linked that can insert and display until now:
struct Node {
int x;
Node *next;
};
This is my initialisation function which only will be called for the first Node:
void initNode(struct Node *head, int n){
head->x = n;
head->next = NULL;
}
To add the Node, and I think the reason why my linked list isn't working correct is in this function:
void addNode(struct Node *head, int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode -> next = head;
head = NewNode;
}
My main function:
int _tmain(int argc, _TCHAR* argv[])
{
struct Node *head = new Node;
initNode(head, 5);
addNode(head, 10);
addNode(head, 20);
return 0;
}
Let me run the program as I think it works. First I initialise the head Node as a Node like this:
head = [ 5 | NULL ]
Then I add a new node with n = 10 and pass head as my argument.
NewNode = [ x | next ] where next points at head. And then I change the place where head is pointing to NewNode, since NewNode is the first Node in LinkedList now.
Why isn't this working? I would appreciate any hints that could make me move in the right direction. I think LinkedList is a bit hard to understand.
When I'm printing this, it only returns 5:
This is the most simple example I can think of in this case and is not tested. Please consider that this uses some bad practices and does not go the way you normally would go with C++ (initialize lists, separation of declaration and definition, and so on). But that are topics I can't cover here.
#include <iostream>
using namespace std;
class LinkedList{
// Struct inside the class LinkedList
// This is one node which is not needed by the caller. It is just
// for internal work.
struct Node {
int x;
Node *next;
};
// public member
public:
// constructor
LinkedList(){
head = NULL; // set head to NULL
}
// destructor
~LinkedList(){
Node *next = head;
while(next) { // iterate over all elements
Node *deleteMe = next;
next = next->next; // save pointer to the next element
delete deleteMe; // delete the current entry
}
}
// This prepends a new value at the beginning of the list
void addValue(int val){
Node *n = new Node(); // create new Node
n->x = val; // set value
n->next = head; // make the node point to the next node.
// If the list is empty, this is NULL, so the end of the list --> OK
head = n; // last but not least, make the head point at the new node.
}
// returns the first element in the list and deletes the Node.
// caution, no error-checking here!
int popValue(){
Node *n = head;
int ret = n->x;
head = head->next;
delete n;
return ret;
}
// private member
private:
Node *head; // this is the private member variable. It is just a pointer to the first Node
};
int main() {
LinkedList list;
list.addValue(5);
list.addValue(10);
list.addValue(20);
cout << list.popValue() << endl;
cout << list.popValue() << endl;
cout << list.popValue() << endl;
// because there is no error checking in popValue(), the following
// is undefined behavior. Probably the program will crash, because
// there are no more values in the list.
// cout << list.popValue() << endl;
return 0;
}
I would strongly suggest you to read a little bit about C++ and Object oriented programming. A good starting point could be this: http://www.galileocomputing.de/1278?GPP=opoo
EDIT: added a pop function and some output. As you can see the program pushes 3 values 5, 10, 20 and afterwards pops them. The order is reversed afterwards because this list works in stack mode (LIFO, Last in First out)
You should take reference of a head pointer. Otherwise the pointer modification is not visible outside of the function.
void addNode(struct Node *&head, int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode -> next = head;
head = NewNode;
}
I'll join the fray. It's been too long since I've written C. Besides, there's no complete examples here anyway. The OP's code is basically C, so I went ahead and made it work with GCC.
The problems were covered before; the next pointer wasn't being advanced. That was the crux of the issue.
I also took the opportunity to make a suggested edit; instead of having two funcitons to malloc, I put it in initNode() and then used initNode() to malloc both (malloc is "the C new" if you will). I changed initNode() to return a pointer.
#include <stdlib.h>
#include <stdio.h>
// required to be declared before self-referential definition
struct Node;
struct Node {
int x;
struct Node *next;
};
struct Node* initNode( int n){
struct Node *head = malloc(sizeof(struct Node));
head->x = n;
head->next = NULL;
return head;
}
void addNode(struct Node **head, int n){
struct Node *NewNode = initNode( n );
NewNode -> next = *head;
*head = NewNode;
}
int main(int argc, char* argv[])
{
struct Node* head = initNode(5);
addNode(&head,10);
addNode(&head,20);
struct Node* cur = head;
do {
printf("Node # %p : %i\n",(void*)cur, cur->x );
} while ( ( cur = cur->next ) != NULL );
}
compilation: gcc -o ll ll.c
output:
Node # 0x9e0050 : 20
Node # 0x9e0030 : 10
Node # 0x9e0010 : 5
Below is a sample linkedlist
#include <string>
#include <iostream>
using namespace std;
template<class T>
class Node
{
public:
Node();
Node(const T& item, Node<T>* ptrnext = NULL);
T value;
Node<T> * next;
};
template<class T>
Node<T>::Node()
{
value = NULL;
next = NULL;
}
template<class T>
Node<T>::Node(const T& item, Node<T>* ptrnext = NULL)
{
this->value = item;
this->next = ptrnext;
}
template<class T>
class LinkedListClass
{
private:
Node<T> * Front;
Node<T> * Rear;
int Count;
public:
LinkedListClass();
~LinkedListClass();
void InsertFront(const T Item);
void InsertRear(const T Item);
void PrintList();
};
template<class T>
LinkedListClass<T>::LinkedListClass()
{
Front = NULL;
Rear = NULL;
}
template<class T>
void LinkedListClass<T>::InsertFront(const T Item)
{
if (Front == NULL)
{
Front = new Node<T>();
Front->value = Item;
Front->next = NULL;
Rear = new Node<T>();
Rear = Front;
}
else
{
Node<T> * newNode = new Node<T>();
newNode->value = Item;
newNode->next = Front;
Front = newNode;
}
}
template<class T>
void LinkedListClass<T>::InsertRear(const T Item)
{
if (Rear == NULL)
{
Rear = new Node<T>();
Rear->value = Item;
Rear->next = NULL;
Front = new Node<T>();
Front = Rear;
}
else
{
Node<T> * newNode = new Node<T>();
newNode->value = Item;
Rear->next = newNode;
Rear = newNode;
}
}
template<class T>
void LinkedListClass<T>::PrintList()
{
Node<T> * temp = Front;
while (temp->next != NULL)
{
cout << " " << temp->value << "";
if (temp != NULL)
{
temp = (temp->next);
}
else
{
break;
}
}
}
int main()
{
LinkedListClass<int> * LList = new LinkedListClass<int>();
LList->InsertFront(40);
LList->InsertFront(30);
LList->InsertFront(20);
LList->InsertFront(10);
LList->InsertRear(50);
LList->InsertRear(60);
LList->InsertRear(70);
LList->PrintList();
}
Both functions are wrong. First of all function initNode has a confusing name. It should be named as for example initList and should not do the task of addNode. That is, it should not add a value to the list.
In fact, there is not any sense in function initNode, because the initialization of the list can be done when the head is defined:
Node *head = nullptr;
or
Node *head = NULL;
So you can exclude function initNode from your design of the list.
Also in your code there is no need to specify the elaborated type name for the structure Node that is to specify keyword struct before name Node.
Function addNode shall change the original value of head. In your function realization you change only the copy of head passed as argument to the function.
The function could look as:
void addNode(Node **head, int n)
{
Node *NewNode = new Node {n, *head};
*head = NewNode;
}
Or if your compiler does not support the new syntax of initialization then you could write
void addNode(Node **head, int n)
{
Node *NewNode = new Node;
NewNode->x = n;
NewNode->next = *head;
*head = NewNode;
}
Or instead of using a pointer to pointer you could use a reference to pointer to Node. For example,
void addNode(Node * &head, int n)
{
Node *NewNode = new Node {n, head};
head = NewNode;
}
Or you could return an updated head from the function:
Node * addNode(Node *head, int n)
{
Node *NewNode = new Node {n, head};
head = NewNode;
return head;
}
And in main write:
head = addNode(head, 5);
The addNode function needs to be able to change head. As it's written now simply changes the local variable head (a parameter).
Changing the code to
void addNode(struct Node *& head, int n){
...
}
would solve this problem because now the head parameter is passed by reference and the called function can mutate it.
head is defined inside the main as follows.
struct Node *head = new Node;
But you are changing the head in addNode() and initNode() functions only. The changes are not reflected back on the main.
Make the declaration of the head as global and do not pass it to functions.
The functions should be as follows.
void initNode(int n){
head->x = n;
head->next = NULL;
}
void addNode(int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode->next = head;
head = NewNode;
}
I think that, to make sure the indeep linkage of each node in the list, the addNode method must be like this:
void addNode(struct node *head, int n) {
if (head->Next == NULL) {
struct node *NewNode = new node;
NewNode->value = n;
NewNode->Next = NULL;
head->Next = NewNode;
}
else
addNode(head->Next, n);
}
Use:
#include<iostream>
using namespace std;
struct Node
{
int num;
Node *next;
};
Node *head = NULL;
Node *tail = NULL;
void AddnodeAtbeggining(){
Node *temp = new Node;
cout << "Enter the item";
cin >> temp->num;
temp->next = NULL;
if (head == NULL)
{
head = temp;
tail = temp;
}
else
{
temp->next = head;
head = temp;
}
}
void addnodeAtend()
{
Node *temp = new Node;
cout << "Enter the item";
cin >> temp->num;
temp->next = NULL;
if (head == NULL){
head = temp;
tail = temp;
}
else{
tail->next = temp;
tail = temp;
}
}
void displayNode()
{
cout << "\nDisplay Function\n";
Node *temp = head;
for(Node *temp = head; temp != NULL; temp = temp->next)
cout << temp->num << ",";
}
void deleteNode ()
{
for (Node *temp = head; temp != NULL; temp = temp->next)
delete head;
}
int main ()
{
AddnodeAtbeggining();
addnodeAtend();
displayNode();
deleteNode();
displayNode();
}
In a code there is a mistake:
void deleteNode ()
{
for (Node * temp = head; temp! = NULL; temp = temp-> next)
delete head;
}
It is necessary so:
for (; head != NULL; )
{
Node *temp = head;
head = temp->next;
delete temp;
}
Here is my implementation.
#include <iostream>
using namespace std;
template< class T>
struct node{
T m_data;
node* m_next_node;
node(T t_data, node* t_node) :
m_data(t_data), m_next_node(t_node){}
~node(){
std::cout << "Address :" << this << " Destroyed" << std::endl;
}
};
template<class T>
class linked_list {
public:
node<T>* m_list;
linked_list(): m_list(nullptr){}
void add_node(T t_data) {
node<T>* _new_node = new node<T>(t_data, nullptr);
_new_node->m_next_node = m_list;
m_list = _new_node;
}
void populate_nodes(node<T>* t_node) {
if (t_node != nullptr) {
std::cout << "Data =" << t_node->m_data
<< ", Address =" << t_node->m_next_node
<< std::endl;
populate_nodes(t_node->m_next_node);
}
}
void delete_nodes(node<T>* t_node) {
if (t_node != nullptr) {
delete_nodes(t_node->m_next_node);
}
delete(t_node);
}
};
int main()
{
linked_list<float>* _ll = new linked_list<float>();
_ll->add_node(1.3);
_ll->add_node(5.5);
_ll->add_node(10.1);
_ll->add_node(123);
_ll->add_node(4.5);
_ll->add_node(23.6);
_ll->add_node(2);
_ll->populate_nodes(_ll->m_list);
_ll->delete_nodes(_ll->m_list);
delete(_ll);
return 0;
}
link list by using node class and linked list class
this is just an example not the complete functionality of linklist, append function and printing a linklist is explained in the code
code :
#include<iostream>
using namespace std;
Node class
class Node{
public:
int data;
Node* next=NULL;
Node(int data)
{
this->data=data;
}
};
link list class named as ll
class ll{
public:
Node* head;
ll(Node* node)
{
this->head=node;
}
void append(int data)
{
Node* temp=this->head;
while(temp->next!=NULL)
{
temp=temp->next;
}
Node* newnode= new Node(data);
// newnode->data=data;
temp->next=newnode;
}
void print_list()
{ cout<<endl<<"printing entire link list"<<endl;
Node* temp= this->head;
while(temp->next!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
cout<<temp->data<<endl;;
}
};
main function
int main()
{
cout<<"hello this is an example of link list in cpp using classes"<<endl;
ll list1(new Node(1));
list1.append(2);
list1.append(3);
list1.print_list();
}
thanks ❤❤❤
screenshot https://i.stack.imgur.com/C2D9y.jpg