It will not show the string char array in non-reverse order (cde), but it does display the array in reverse order (edc). Could you please help with why it isn't displaying the cde?
I tried changing variable names, but I'm a new programmer so I don't really know yet what to do.
#include <iostream>
using namespace std;
// of linked list in reverse order
// Structure of a node
template<class T>
struct listrec2
{
T value; //corresponds to data
listrec2 *next; //points to next node
listrec2 *prev; //points to previous nod
};
template<class T>
void downwardSearch(listrec2<T> *head)
//traverse from start of linked list to end of linked list
//print out value of each node along way
{
char s[] = { 'c', 'd', 'e' };
// if you wanted to make it in the function listrec2<T> *tail;
listrec2<T> *current;
listrec2<T> *tail;
listrec2<T> value;
head = tail = new listrec2<T>; // make a new node
head->value = s[0];
tail = NULL;
head = NULL;
for (int i = 1; i < strlen(s); i++)
{
current = new listrec2<T>; //makes new node
current->value = s[i];
current->next = NULL;
current->prev = tail;
tail->next = current;
tail = current;
}
listrec2<T> *ptr;
ptr = head;
cout << "The array in non-reverse order: " << endl;
while (ptr != NULL)
{
cout << ptr->value;
ptr = ptr->next;
}
}
template<class T>
void upwardSearch(listrec2<T> *tail)
{
char s[] = { 'c', 'd', 'e' };
// if you wanted to make it in the function listrec2<T> *tail;
// listrec2<T> *temp;
listrec2<T> *current2;
listrec2<T> *tail2;
listrec2<T> *value;
listrec2<T> *head2;
head2 = tail = new listrec2<T>; // make a new node
head2->value = s[0];
tail2 = NULL;
head2 = NULL;
for (int i = 1; i < strlen(s); i++)
{
current2 = new listrec2<T>;
current2->value = s[i];
current2->next = NULL;
current2->prev = tail;
tail->next = current2;
tail = current2;
}
listrec2<T> *ptr2;
ptr2 = tail;
cout << "The array in reverse order or backwards: " << endl;
while (ptr2 != NULL)
{
cout << ptr2->value;
ptr2 = ptr2->prev;
}
cout << endl;
}
int main()
{
//missing info here
listrec2<char> *head;
listrec2<char> *tail;
upwardSearch(head);
downwardSearch(tail);
return 0;
}
The expected results are: the array before reversal: cde
the array after reversa: edc.
Here is one way of doing it with a create_list, search_up, search_down, and destory_list functions. I try to use variable names that are more descriptive. I do not like listrec2 because it is very confusing. It makes me think of the second node, but that is not what it is. It is a node type.
Also, it is a good habbit to capitalize your types (e.g. Node). Then, you can use the lowercase version for the object (e.g. Node node;)
#include <iostream>
using namespace std;
// of linked list in reverse order
// Structure of a Node
template<class T>
struct Node {
T value; //corresponds to data
Node *next; //points to next Node
Node *prev; //points to previous nod
};
template<typename T>
void CreateList(Node<T> *&head, Node<T> *&tail, T value_array[], int array_size)
{
head = nullptr;
tail = nullptr;
for (int i = 0; i < array_size; i++) {
// Create new node and add node to the end of the list
Node<T> *node = new Node<T>();
node->next = nullptr;
node->prev = tail;
if (head == nullptr) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
node->value = value_array[i];
}
}
template<class T>
void downwardSearch(Node<T> *head)
//traverse from start of linked list to end of linked list
//print out value of each Node along way
{
Node<T> *ptr = head;
cout << "The array in forward order: " << endl;
while (ptr != nullptr) {
cout << ptr->value;
ptr = ptr->next;
}
}
template<class T>
void DestroyList(Node<T> *head)
{
Node<T> *ptr;
while (head != nullptr) {
ptr = head->next;
delete head;
head = ptr;
}
}
template<class T>
void upwardSearch(Node<T> *tail)
{
Node<T> *ptr = tail;
cout << "The array in reverse order or backwards: " << endl;
while (ptr != nullptr) {
cout << ptr->value;
ptr = ptr->prev;
}
cout << endl;
}
int main()
{
char s[] = {'c', 'd', 'e'};
Node<char> *head;
Node<char> *tail;
CreateList<char>(head, tail, s, 3);
upwardSearch(tail);
downwardSearch(head);
DestroyList(head);
head = tail = nullptr;
return 0;
}
Related
as shown in the code , i have to use 2 similar functions for creating 2 linked lists . isn't there a way i can create as many lists as i want with just one function , i tried using struct Node **p and struct Node *p as a parameter to the function but the didn't work
can someone help me to create multiple linked lists using this same function
and i want to create a append function not a insert function which asks for position as well.
#include <iostream>
using namespace std;
struct Node
{
int data = 10 ;
struct Node *next;
} *first , *second , *third;
void Display(struct Node *p)
{
while (p)
{
cout<<p->data<<" ";
p = p->next ;
}
cout<<"\n";
}
void Append_1(int elem)
{
Node* t , *last;
t = new Node;
t->data = elem;
t->next = NULL;
if(first == 0)
first = last = t;
else
{
last->next = t;
last = t;
}
}
void Append_2(int elem)
{
Node* t , *last;
t = new Node;
t->data = elem;
t->next = NULL;
if(second == 0)
second = last = t;
else
{
last->next = t;
last = t;
}
}
//void SortMerge(struct Node *p , struct Node *q);
int main()
{
Append_1(3);
Append_1(7);
Display(first);
Append_2(10);
Append_2(14);
Append_2(21);
Display(second);
//SortMerge(first , second);
Display(third);
return 0;
}
You can create a class like here:
struct Node{
int data;
Node* next;
Node* previous;
};
class Graph{
public:
Graph(int = 0);
~Graph();
void display_left_right();
void display_right_left();
void append(int);
void append_at_pos(int,int);
void prepend(int);
int get_num_elt();
int get_data_at_pos(int);
private:
Node* head;
Node* tail;
int num_elt=0;
};
Graph::Graph(int first_data){
head = new Node;
head->next = NULL;
head->previous = NULL;
head->data = first_data;
tail = head;
num_elt++;
}
Graph::~Graph(){
Node* main_traverser = head;
while(main_traverser){
main_traverser = head->next;
delete head;
head = main_traverser;
}
std::cout <<"Graph deleted!" << std::endl;
}
void Graph::display_left_right(){
Node* traverser = head;
while(traverser != NULL){
std::cout << traverser->data << " ";
traverser = traverser->next;
}
std::cout << std::endl;
}
void Graph::display_right_left(){
Node* traverser = tail;
while(traverser != NULL){
std::cout << traverser->data << " ";
traverser = traverser->previous;
}
std::cout << std::endl;
}
void Graph::append(int new_data){
Node* add = new Node;
add->data = new_data;
add->next = NULL;
add->previous = tail;
tail->next = add;
tail = add;
num_elt++;
}
void Graph::append_at_pos(int pos, int new_data){
if(pos > num_elt+1 || pos<=0){std::cout << "Wrong position!" << std::endl; return;}
if(pos==1){
prepend(new_data);
return;
}
if(pos==num_elt+1){
append(new_data);
return;
}
Node* add = new Node;
Node* traverser = head;
add->data = new_data;
for(int i=0; i<pos-2; i++){
traverser = traverser->next;
}
add->next = traverser->next;
add->previous = traverser;
traverser->next->previous = add;
traverser->next = add;
}
void Graph::prepend(int new_data){
Node* add = new Node;
add->next = head;
add->previous = NULL;
add->data = new_data;
head->previous = add;
head = add;
num_elt++;
}
int Graph::get_num_elt(){
return num_elt;
}
int Graph::get_data_at_pos(int pos){
Node* traverser = head;
if(pos <=0 || pos> num_elt){std::cout << "Wrong position!" << std::endl; return 0;}
for(int i=0; i<pos-1; i++){
traverser = traverser->next;
}
return traverser->data;
}
main(){
Graph a(2);
a.append(3);
a.append(4);
a.prepend(1);
a.display_left_right();
a.append_at_pos(1,6);
a.display_left_right();
std::cout << "data at 1: " << a.get_data_at_pos(1) << std::endl;
}
When you say "create multiple linked lists," I think you mean creating nodes to a linked list, which you have 2 append functions. I think the reason you have these 2 functions is because you do not know where to start traversing your linked list. For this reason, I think in your main function you should declare the head of the linked list, a single node that is the start. Set it's data and next to null, and then pass the head value into a function so it can start traversing from the head. Here is a generic append function that adds a node on the end, where the parameters are a reference to the head node, and the value for the new node:
void append(Node ** head, int new_data)
{
Node * select_node = * head;
// select node is set to the head node, and will traverse until it is at the end
while (select_node -> next != NULL)
{
// select node is set to the next node until it is NULL (end of linked list)
select_node = select_node -> next;
}
// now that select node is the last node, we need to make it's next value a node
// and that node should be a new node (allocated in heap) with the value of the input value
//and the next value be NULL (because it's the end of the linked list)
Node * next_node = new Node();
next_node -> data = new_data;
next_node -> next = NULL;
select_node -> next = next_node;
}
I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.
#include <iostream>
class Node {
public:
int data;
Node *next;
Node(int &num) {
this->data = num;
next = NULL;
}
};
class LinkedList {
Node *head = NULL;
public:
void insert(int num) {
Node *tmp;
if (head == NULL) {
head = new Node(num);
tmp = head;
} else {
tmp->next = new Node(num);
tmp = tmp->next;
}
}
void printList() {
Node *tmp = head;
while (tmp) {
std::cout << tmp->data << " ";
tmp = tmp->next;
}
std::cout << std::endl;
}
void reverseList() {
Node *curr = head, *prev = NULL, *nextNode;
while (curr) {
nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
head = prev;
}
};
int main() {
LinkedList list1;
// This is not working
int num;
while (num != -1) {
std::cin >> num;
list1.insert(num);
}
// This is working
// list1.insert(1);
// list1.insert(2);
// list1.insert(3);
// list1.insert(4);
// list1.insert(5);
list1.printList();
list1.reverseList();
list1.printList();
return 0;
}
I expect this after insertion
Edit:
although #Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood?
for (int i = 1; i <= 10; i++)
{
list1.insert(i);
}
When inserting the nth item (1st excluded) tmp is a null pointer, i don't understand what you are doing there, you are assigning to next of some memory then you make that pointer point to another location, losing the pointer next you assigned before, you must keep track of the last item if you want optimal insertion. This way you are only assigning to some *tmp then going out of scope loses all your data... The best way is to just keep a pointer to the last inserted item, no need to use *tmp.
class LinkedList
{
Node *head = NULL;
Node *tail = NULL;
public:
void insert(int num)
{
if (head == NULL)
{
head = new Node(num);
tail = head;
}
else
{
tail->next = new Node(num);
tail = tail->next;
}
}
...
}
You need to loop until you reach the end of the list and then add the new node after that. Like this.
void insert(int num) {
Node *tmp = head;
if (head == NULL) {
head = new Node(num);
}
else {
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = new Node(num);
}
}
first of all you need to define a node for each of the tail and head of the list as follows
Node *h;
Node *t;
you may also separate the Node from the LinkedList class so you can modify easily
class Node{
public:
int data;
Node *next;
Node(int data, Node* next);
~Node();
};
Node::Node(int data, Node* next)
{
this->data= data;
this->next= next;
}
Node::~Node(){}
}
after that you can try to add these functions to your LinkedList class
so it can deal with other special cases such empty list or full, etc..
void addToHead(int data){
Node *x = new Node(data,h);
h=x;
if(t==NULL){
t=x;
}
void addToTail(int data){
Node *x = new Node(data,NULL);
if(isEmpty()){
h=t=x;
}
else
{
t->next=x;
t=x;
}
}
now for the insert function try this after you implemented the Node class and the other functions,
void insert(int v){
if(h==nullptr){addToHead(v); return;}
if(h->data>=v) {addToHead(v);return;}
if(t->data<=v) {addToTail(v); return;}
// In this case there is at least two nodes
Node *k=h->next;
Node *p=h;
while(k != nullptr){
if(k->data >v){
Node *z =new Node(v,k);
p->next=z;
return;
}
p=k;
k=k->next;
}
}
the idea of making all of this is not lose the pointer when it goes through elements in the Linked List so you don't end up with a run time error.
I hope this can be useful to you.
There was an issue with your insert function.
Read about segmentation fault here https://www.geeksforgeeks.org/core-dump-segmentation-fault-c-cpp/#:~:text=Core%20Dump%2FSegmentation%20fault%20is,is%20known%20as%20core%20dump.
for a quick workaround you can use this
using namespace std;
#include <iostream>
class Node
{
public:
int data;
Node *next;
Node(int num)
{
this->data = num;
next = NULL;
}
};
class LinkedList
{
Node *head = NULL;
public:
void insert(int num)
{
Node *tmp= new Node(num);
tmp->next=head;
head=tmp;
}
void printList()
{
Node *tmp = head;
while (tmp)
{
std::cout << tmp->data << " ";
tmp = tmp->next;
}
std::cout << std::endl;
}
void reverseList()
{
Node *curr = head, *prev = NULL, *nextNode;
while (curr)
{
nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
head = prev;
}
};
int main()
{
LinkedList list1;
// This is not working
int num,i=0,n;
cout<<"Type the value of n";
cin>>n;
while (i<n)
{
cin >> num;
cout<<num<<" "<<&num<<endl;
list1.insert(num);
i++;
}
list1.printList();
list1.reverseList();
list1.printList();
return 0;
}
The void reve(struct Node *head) and display(struct Node *head) methods take one argument - the head of the linked list. I want to print the whole linked list but my display function print only 4.
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *link;
};
void display(struct Node *head) {
if (head == NULL) {
return;
}
cout << head->data << "\t";
display(head->link);
//head = head->link;
}
struct Node *reve(struct Node *head) {
struct Node *p = head;
if (p->link == NULL) {
head = p;
return head;
}
reve(p->link);
struct Node *temp = p->link;
temp->link = p;
p->link = NULL;
}
struct Node *insert(struct Node *head, int new_data) {
Node *new_node = new Node();
new_node->data = new_data;
new_node->link = head;
head = new_node;
return head;
}
int main() {
Node *head = NULL;
head = insert(head, 1);
head = insert(head, 2);
head = insert(head, 3);
head = insert(head, 4);
cout << "The linked list is: ";
//display(head);
head = reve(head);
display(head);
return 0;
}
Output
If you want the recursive way:
Node* reverse(Node* head)
{
if (head == NULL || head->next == NULL)
return head;
/* reverse the rest list and put
the first element at the end */
Node* rest = reverse(head->next);
head->next->next = head;
head->next = NULL;
/* fix the head pointer */
return rest;
}
/* Function to print linked list */
void print()
{
struct Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
}
The function reve does not return a value if p->link is not NULL.
Since head has more than 1 element, head = reve(head); has undefined behavior.
Reversing a linked list is much easier to implemented in a simple loop than with recursion:
struct Node *reve(struct Node *p) {
if (p != NULL) {
struct Node *prev = NULL;
while (p->link) {
struct Node *next = p->link;
p->link = prev;
prev = p;
p = next;
}
}
return p;
}
If your task requires recursion, you can make a extract the first node, reverse the remainder of the list and append the first node. Beware that this is not tail recursion, hence any sufficiently long list may cause a stack overflow.
struct Node *reve(struct Node *head) {
if (head != NULL && head->link != NULL) {
struct Node *first = head;
struct Node *second = head->link;
head = reve(second);
first->link = NULL; // unlink the first node
second->link = first; // append the first node
}
return head;
}
In C++ you need not to use keywords struct or class when an already declared structure or a class is used as a type specifier.
The function reve has undefined behavior.
First of all head can be equal to nullptr. In this case this statement
if (p->link == NULL) {
invokes undefined behavior.
Secondly the function returns nothing in the case when p->link is not equal to nullptr.
//...
reve(p->link);
struct Node *temp = p->link;
temp->link = p;
p->link = NULL;
}
Here is a demonstrative program that shows how the functions can be implemented. I used your C approach of including keyword struct when the structure is used as a type specifier.
#include <iostream>
struct Node
{
int data;
struct Node *link;
};
struct Node * insert( struct Node *head, int data )
{
return head = new Node{ data, head };
}
struct Node * reverse( struct Node *head )
{
if ( head && head->link )
{
struct Node *tail = head;
head = reverse( head->link );
tail->link->link = tail;
tail->link = nullptr;
}
return head;
}
std::ostream & display( struct Node *head, std::ostream &os = std::cout )
{
if ( head )
{
os << head->data;
if ( head->link )
{
os << '\t';
display( head->link, os );
}
}
return os;
}
int main()
{
struct Node *head = nullptr;
const int N = 10;
for ( int i = 0; i < N; i++ )
{
head = insert( head, i );
}
display( head ) << '\n';
head = reverse( head );
display( head ) << '\n';
return 0;
}
The program output is
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
display is fine.
First thing I have notices is that you are trying to modify a copied value. For example, line 16. This code has no effect.
Note that you have a bug on insert: You return head instead of new_node.
Your version fails for lists with more than 1 item. reve() is supposed to return the last node of the original list, which you do not, hence lastNode would not point to the last node of the reversed list. So my advice is that you keep it aside.
So, reve:
struct Node* reve(struct Node* head) {
if (head->link == NULL) {
return head;
}
struct Node* lastNode = reve(head->link);
lastNode->link = head;
head->link = NULL;
return head;
}
and main:
int main() {
Node* head = NULL;
Node* last_node = head = insert(head, 1);
head = insert(head, 2);
head = insert(head, 3);
head = insert(head, 4);
head = reve(head);
cout << "The linked list is: ";
// Now, last_node is the new head
display(last_node);
return 0;
}
I am new to linked list..My simple code is to create linked list and insert nodes at the end and traverse it..
My problems are-
1)-Every time insert function is called,head pointer gets null
2)-not working right while going in show function..
Please help..Thanks in advance
#include<iostream>
#include<malloc.h>
using namespace std;
struct linkedList
{
int value;
linkedList *next;
};
linkedList* head = NULL;
void insert(linkedList* head, int data)
{
linkedList *ptr;
linkedList *node;
node = (linkedList*) malloc(sizeof(struct linkedList));
node->value = data;
node->next = NULL;
if (head == NULL)
{
head = node;
}
else
{
ptr = head;
while (ptr != NULL)
{
ptr = ptr->next;
}
ptr = node;
}
}
void show(struct linkedList *head)
{
struct linkedList *ptr;
ptr = head;
while (ptr != NULL)
{
cout << ptr->value << endl;
ptr = ptr->next;
}
}
int main()
{
int size = 5;
int array[size];
for (int i = 0; i < 5; i++)
{
cout << "Enter value" << endl;
cin >> array[i];
insert(head, array[i]);
}
show(head);
}
In your insert() function:
when head is NULL, you are assigning the new node to the local head parameter, which is not updating the caller's head variable. That is why your global head variable is always NULL. This is because you are passing the head parameter by value, so you are assigning the new node to a copy, not the original. You need to pass the parameter by reference/pointer instead.
when head is not NULL, you are not traversing the nodes correctly to find the tail node, so ptr is always NULL after the traversal. You are not setting the next field of the tail node at all.
Also, your main() is leaking the allocated nodes.
Try something more like this instead:
#include <iostream>
struct linkedNode
{
int value;
linkedNode *next;
};
void insertValue(linkedNode* &head, int data)
{
linkedNode *node = new linkedNode;
node->value = data;
node->next = NULL;
if (!head)
{
head = node;
}
else
{
linkedNode *ptr = head;
while (ptr->next)
{
ptr = ptr->next;
}
ptr->next = node;
}
}
void showValues(linkedNode *head)
{
linkedNode *ptr = head;
while (ptr)
{
std::cout << ptr->value << std::endl;
ptr = ptr->next;
}
}
void freeValues(linkedNode* &head)
{
linkedNode *ptr = head;
head = NULL;
while (ptr)
{
linkedNode *next = ptr->next;
delete ptr;
ptr = next;
}
}
int main()
{
linkedNode* mylist = NULL;
for (int i = 0; i < 5; ++i)
{
std::cout << "Enter value" << std::endl;
int value;
if (std::cin >> value)
insertValue(mylist, value);
}
showValues(mylist);
freeValues(mylist);
return 0;
}
That being said, if you keep track of the tail node in the list, inserts at the end would be much faster and efficient since you would not need to traverse the list at all:
#include <iostream>
struct linkedNode
{
int value;
linkedNode *next;
linkedNode(int data)
value(data), next(NULL)
{
}
};
struct linkedList
{
linkedNode *head;
linkedNode *tail;
linkedList()
: head(NULL), tail(NULL)
{
}
~linkedList()
{
linkedNode *ptr = head;
while (ptr)
{
linkedNode *next = ptr->next;
delete ptr;
ptr = next;
}
}
void insert(int data)
{
linkedNode *node = new linkedNode(data);
if (!head)
head = node;
if (tail)
tail->next = node;
tail = node;
}
void showValues()
{
linkedNode *ptr = head;
while (ptr)
{
std::cout << ptr->value << std::endl;
ptr = ptr->next;
}
}
};
int main()
{
linkedList mylist;
for (int i = 0; i < 5; ++i)
{
std::cout << "Enter value" << std::endl;
int value;
if (std::cin >> value)
mylist.insert(value);
}
mylist.showValues();
return 0;
}
In which case, you could just throw all of this away and use the standard std::list class instead:
#include <iostream>
#include <list>
#include <algorithm>
void showValue(int value)
{
std::cout << value << std::endl;
}
void showValues(const std::list<int> &values)
{
std::for_each(values.begin(), values.end(), showValue);
/* or, if you are using C++11:
std::for_each(values.begin(), values.end(),
[](int value){ std::cout << value << std::endl; }
);
*/
}
int main()
{
std::list<int> mylist;
for (int i = 0; i < 5; ++i)
{
std::cout << "Enter value" << std::endl;
int value;
if (std::cin >> value)
mylist.push_back(value);
}
showValues(mylist);
return 0;
}
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