I am not getting how to run the concatenate function using both Node and LinkedList as classes. If anyone knows how to do it, please let me know.
Here I have created two classes one for linked list and the former one for Node creation.
Using create function and passing array as Linked list input. Also, I am getting the headref using getHead() and getHead2() functions which give the starting pointer of first and second Linked List respectively.
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(){
data=0;
next=NULL;
}
Node(int data){
this->data=data;
this->next=NULL;
}
};
class LL{
Node* first, *second;
public:
LL(){
first=second=NULL;
}
void create(int arr[], int n){
Node* t, *last;
first=new Node();
first->data= arr[0];
first->next=NULL;
last=first;
for(int i=1;i<n;i++){
t=new Node();
t->data=arr[i];
t->next=NULL;
last->next=t;
last=t;
}
}
void create2(int arr[], int n){
Node* t, *last;
second=new Node();
second->data= arr[0];
second->next=NULL;
last=second;
for(int i=1;i<n;i++){
t=new Node();
t->data=arr[i];
t->next=NULL;
last->next=t;
last=t;
}
}
Node* getHead(){
return first;
}
Node* getHead2(){
return second;
}
void display(Node* p){
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void concatLL(){
Node* p=first;
while(p->next){
p=p->next;
}
p->next=second;
second=NULL;
}
};
int main()
{
LL l,l2;
int arr[]={1,2,3,4,5,6,7};
int arr2[]={2,5,7,8,9};
int n=sizeof(arr)/sizeof(arr[0]);
int n2=sizeof(arr2)/sizeof(arr2[0]);
l.create(arr,n);
l2.create2(arr2,n2);
cout<<"Displaying first LL"<<endl;
l.display(l.getHead());
cout<<"Displaying second LL"<<endl;
l2.display(l2.getHead2());
cout<<"Displaying Linked list after concatination"<<endl;
l.concatLL();
l.display(l.getHead());
return 0;
}
p is equal to NULL when executing p->next=second; in concatLL() causing undefined behaviour since the while loop runs until p == NULL. You should use while(p->next) instead of while(p) and check that first is not a null pointer before.
A linked list is still a Node, and as others said, at the end of your while loop p is pointed to NULL. You can't NULL->second=second neither NULL=second, so change your while loop stop condition:
void concatLL(){
Node* p=first;
while(p->next){
p=p->next;
}
p->next=second;
second=NULL;
}
};
Here is my solution:
#include <iostream>
using namespace std;
struct Node {
Node* next;
int value;
Node(int value) {
this->value = value;
this->next = NULL;
}
Node(int n, int a[]) {
value = a[0];
next = NULL;
Node* p = this;
for (int i = 1; i < n; i++) {
p->next = new Node(a[i]);
p = p->next;
}
}
void concat(Node* head) {
Node* p = this;
while (p->next != NULL) {
p = p->next;
}
p->next = head;
}
void display() {
Node* current = this;
while (current != nullptr) {
cout << current->value << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
int a[] = { 1, 2, 3, 4, 5 };
int b[] = { 6, 7, 8, 9, 10 };
Node* list1 = new Node(5, a);
Node* list2 = new Node(5, b);
list1->display();
list2->display();
list1->concat(list2);
list1->display();
return 0;
}
Related
I had created a program to create a linked list and insert an array in it. But it's not giving the desired output, may be the problem is in display function
#include <iostream>
using namespace std;
//node
class node {
public:
int data;
node *next;
} *head = nullptr;
//function to insert array in linkedlist
void create(int A[], int n) {
node *head = new node;
node *temp;
node *last;
head->data = A[0];
head->next = nullptr;
last = head;
for (int i = 1; i < n; i++) {
//temp is an temporary variable which creates each time and last remebers its position
temp = new node;
temp->data = A[i];
cout << temp->data << endl;
temp->next = nullptr;
last->next = temp;
last = temp;
}
}
//function to display linked list which can access head because it is global
void display() {
node *p = head;
while (p != nullptr) {
cout << p->data << endl;
p = p->next;
}
}
int main() {
int A[] = {1, 6, 9, 4, 5, 6};
node *head;
create(A, 6);
display();
return 0;
}
Maybe I understand something wrong like to add display function in class. But I had never seen a class pointer having functions.
This is my first linked list program. If you could share some good info about it please do, thank you
The problem is that you have multiple variables named head being used for different purposes. You have a global variable head, which your display() function uses, but your create() function does not populate. create() populates a local variable named head instead, which shadows the global variable. display() never sees the created list. And main() has its own local variable named head, which is not being used for anything at all.
Get rid of the global variable. Make create() return the list it creates. And then make main() pass that list to display().
Try something like this:
#include <iostream>
using namespace std;
//node
class node {
public:
int data;
node *next;
};
//function to insert array in linkedlist
node* create(int A[], int n) {
node *head = nullptr;
node **p = &head;
for (int i = 0; i < n; i++) {
*p = new node{ A[i], nullptr };
p = &((*p)->next);
}
return head;
}
//function to display linked list
void display(const node *head) {
node *p = head;
while (p != nullptr) {
cout << p->data << endl;
p = p->next;
}
}
//function to destroy linked list
void destroy(node *head) {
node *p = head;
while (p != nullptr) {
node *next = p->next;
delete p;
p = next;
}
}
int main() {
int A[] = {1, 6, 9, 4, 5, 6};
node *head = create(A, 6);
display(head);
destroy(head);
return 0;
}
I'm new to c++ and I use c++ to learn data structure recently. I stuck when the error occurs, I've tried to debug but It's still confused me. So, this error is I try to implement two operations concatenate and merge, my terminal shows the result that seems to successful on logical. However, the error is coming in the next second.
Just like img:enter image description here call stack
Here is my code. Hopefully, someone can help me solve this issue, thanks!
#pragma once
#include <iostream>
using namespace std;
class LinkedList;
class Node
{
private:
int data;
Node* next;
public:
friend class LinkedList;
};
class LinkedList
{
private:
Node* first;
Node* last;
Node* third;
public:
LinkedList()
{
first = nullptr;
last = nullptr;
third = nullptr;
}
LinkedList(int A[], int n);
~LinkedList();
void Display();
void RDisplay();//Recursive
void RDisplay(Node* p);
Node* getFirstNode();
int Count();
int RCount(Node* p);//Recursive
int Sum();
int RSum(Node* p);//Recursive
int Max();
int RMax(Node* p);//Recursive
int LSearch(int key); //linear search
int RSearch(int key);
int RSearch(Node* p, int key);
void Insert(int position, int x);
void InsertLast(int x);
void SortedInsert(int x);
int Delete(int position);
int isSorted();
void RemoveDuplicate();
void ReverseE();//Elements
void ReverseL();//Links
void RReverse();//Recursive
void RReverse(Node* q,Node *p);
void Concatenate(Node* second);
void Merge(Node *second);
int Mid();
int isLoop();
};
//cpp file
#include "Linkedlist.h"
#include <iostream>
using namespace std;
LinkedList::LinkedList(int A[], int n)
{
Node* t ;
first = new Node;
first->data = A[0];
first -> next = nullptr;
last = first;
for (int i = 1; i < n; i++)
{
t = new Node;
t->data = A[i];
t->next = nullptr;
last->next = t;
last = t;
}
}
LinkedList ::~LinkedList()
{
Node* p = first;
while (first)
{
first = first->next;
delete p;
p = first;
}
}
void LinkedList::Merge(Node* second)
{
Node* last;
if (first->data < second->data)
{
third = first;
last = first;
first = first->next;
last->next = nullptr;
}
else
{
third = last = second;
second = second->next;
last->next = NULL;
}
while (first != NULL && second != NULL)
{
if (first->data < second->data)
{
last->next = first;
last = first;
first = first->next;
last->next = NULL;
}
else
{
last->next = second;
last = second;
second = second->next;
last->next = NULL;
}
}
if (first != NULL)
{
last->next = first;
first = third;
}
else
{
last->next = second;
first = third;
}
}
//concatenate
void LinkedList::Concatenate(Node* second)
{
Node* p = first;
while (p->next != NULL)
{
p = p->next;
}
p->next = second;
}
void LinkedList::Display()
{
Node* p = first;
while (p != nullptr)
{
cout << p->data << " -> ";
p = p->next;
}
}
Node* LinkedList::getFirstNode()
{
return first;
}
#include <iostream>
#include "Linkedlist.h"
#include "Circular.h"
#include "Doubly.h"
#include "CircularDoubly.h"
int main()
{
int A[] = { 1,2,3,4,6,7 };
int B[] = { 5,6,7,8 };
LinkedList c1(A,6);
LinkedList c2(B, 4);
c1.Concatenate(c2.getFirstNode());
c1.Display();
}
Should I offer more detail?
stack call
stack call2
Yes it's the problem in destructor, after Concatenate, the c2 list has been appended to c1 list, the elements are destroyed twice, once in c1's destructor, the second time in c2's destructor. This is a memory issue that may lead to a crash.
I suggest fix it like this:
Transfer the ownership to c1, then we avoid destroy twice
Node* LinkedList::ReleaseFirst() {
Node* tmp = first;
first = nullptr;
return tmp;
}
c1.Concatenate(c2.ReleaseFirst());
Online demo
I need to define a class of linked list,List, in a way such that object of class can be defined in two ways,
List obj1 = L1();//head=0
List obj2 = L2(given_arr[], size of array) // I would be given an array, whose elements are elements of list
so, I need to form a construter for both,
for obj1, Its easy.
List(){head=0};
But I am not abe to do so for second type of object.
I tried to form a program for this.
#include <iostream>
using namespace std;
class List {
class node {
public:
int val;
node* next;
};
public:
node* head;
int arr[];
List() { head = 0; }
List(int arr[], int size);
void addnode(int value) {
node* newnode = new node();
newnode->val = value;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
} else {
node* temp = head; // head is not NULL
while (temp->next != NULL) {
temp = temp->next; // go to end of list
}
temp->next = newnode; // linking to newnode
}
}
void display() {
if (head == NULL) {
cout << "List is empty!" << endl;
} else {
node* temp = head;
while (temp != NULL) {
cout << temp->val << " ";
temp = temp->next;
}
cout << endl;
}
}
};
List::List(int arr[], int size) {
int i;
head->val = arr[0];
for (i = 0; i < size; i++) addnode(arr[i]);
}
int main() {
int barr[4] = {9, 89, 0, 43};
List* M = new List();
List* L = new List(barr[4], 4);
L->display();
return 0;
}
This program doesn't work. Please suggest a way to do so.
Make these changes to your main().
int main() {
int barr[] = {9, 89, 0, 43}; // No need to specify size if you're initializing
// List* M = new List(); // unused
// Your array is barr, barr[4] makes no sense. You also don't allocate the List,
// the list allocates
List L = List(barr, sizeof(barr) / sizeof(barr[0]);
L.display(); // -> to .
return 0;
}
This now compiles, but immediately segfaults. Simply running the program in the debugger shows a simple error. The line head->val = arr[0]; attempts to dereference a null pointer. Which takes us to the next thing. Use nullptr, not NULL or 0.
Your array constructor was over-complicated, you just need this:
List::List(int arr[], int size) {
for (int i = 0; i < size; i++) addnode(arr[i]);
}
Your addnode() function already handled an empty list. Fixing that, your code should run. I made a couple other small changes, mostly trimming cruft out. Here's your complete code:
#include <iostream>
using namespace std;
class List {
class node {
public:
int val;
node* next;
};
public:
node* head = nullptr;
List() = default;
List(int arr[], int size);
void addnode(int value) {
node* newnode = new node();
newnode->val = value;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
} else {
node* temp = head; // head is not NULL
while (temp->next != NULL) {
temp = temp->next; // go to end of list
}
temp->next = newnode; // linking to newnode
}
}
void display() {
if (head == NULL) {
cout << "List is empty!" << endl;
} else {
node* temp = head;
while (temp != NULL) {
cout << temp->val << " ";
temp = temp->next;
}
cout << endl;
}
}
};
List::List(int arr[], int size) {
for (int i = 0; i < size; i++) addnode(arr[i]);
}
int main() {
int barr[] = {9, 89, 0, 43};
List L = List(barr, sizeof(barr) / sizeof(barr[0]));
L.display();
return 0;
}
I want to remove one node from a Circular Single Linked List and when i reach to the Cmd, it shows me an address (maybe) which is repeating infintely. Please help me or show me what is wrong. Here is the code in C++
using namespace std;
class Node{
private:
int data;
Node * next;
public:
void setdata(int s);
int getdata()
{
return data;
}
void setnext(Node * next_pointer);
Node * getnext();
};
void Node::setdata(int s){
data = s;
}
Node * Node::getnext(){
return this->next;
}
void Node::setnext(Node *next_node)
{
this->next = next_node;
}
class Circular{
private:
Node * first;
int sizen;
public:
Circular();
void append(int value);
void display();
Node * walk(int start, int die=3);
int remove_node(Node * prev_node);
int getsize();
Node * get_first();
void removing(int val);
};
Circular::Circular(){
first = 0;
sizen = 0;
}
void Circular::append(int val)
{
Node * new_node = new Node;
new_node -> setdata(val);
if(this->sizen == 0 )
{
//There is empty
this->first = new_node;
this->first -> setnext(this->first);
this->sizen = 1;
}
else
{
//It's not empty
Node *node = this->first;
while(node->getnext()!= this->first)
{
node = node->getnext();
}
node->setnext(new_node);
node->getnext() -> setnext(this->first);
this->sizen +=1;
}
}
void Circular::display()
{
Node *temp = this->first;
std::cout<<temp->getdata()<<" ";
temp = temp->getnext();
while(temp!=this->first)
{
std::cout<<temp->getdata()<<" ";
temp = temp->getnext();
}
}
void Circular::removing(int val)
{
Node *new_node = this->first, *d;
/*if(new_node->sizen==0)
return 0;
if(new_node->sizen==1 && new_node->getdata() == val)
{free(new_node);
return 0;
}*/
std::cout<<"Removing "<<val<<std::endl;
while((new_node->getnext())->getdata()!=val)
{
new_node = new_node->getnext();
}
if((new_node->getnext())->getdata()==val)
{
d = new_node->getnext();
new_node->getnext() ->setnext(d->getnext());
free(d);
}
}
int Circular::getsize(){
Node *temp = this->first;
int length = 0;
length++;
while(temp->getnext()!=this->first)
{
temp = temp->getnext();
length++;
}
return length;
}
int main(){
Circular l;
int i, n,k;
std::cout<<"How many participants do you want? ";
std::cin>>n;
std::cout<<"Which participant should be killed? (Kth)";
std:cin>>k;
for(i=1;i<=n;i++)
l.append(i);
l.display();
l.removing(2);
l.display();
}
And Here is where the problem gets me anxious:
void Circular::removing(int val)
{
Node *new_node = this->first, *d;
/*if(new_node->sizen==0)
return 0;
if(new_node->sizen==1 && new_node->getdata() == val)
{free(new_node);
return 0;
}*/
std::cout<<"Removing "<<val<<std::endl;
while((new_node->getnext())->getdata()!=val)
{
new_node = new_node->getnext();
}
if((new_node->getnext())->getdata()==val)
{
d = new_node->getnext();
new_node->getnext() ->setnext(d->getnext());
free(d);
}
}
I have no error and when I run the program, I want to remove the Second (2) node, but it shows me:
1 1114304 1114304 1114304 1114304 1114304 and so on.
THs following code is crashing, and I'm unsure why. Trying to count the number of times an integer is found in the following linked list..However xcode keeps saying the int count=0 from the main is breaking a thread?
#include <iostream>
using namespace std;
struct Node {
int val;
Node *next;
};
int countNum (Node *head, int key);
Node* cons (int x, Node* p);
int main()
{
Node *head = (1,cons(2,cons(2,(cons(4,(cons(5,nullptr)))))));
int counts=0;
counts= countNum(head,2);
cout<< counts<< head;
return 0;
}
Node* cons (int x, Node* p){
Node *q=new Node;
q->val=x;
q->next=p;
return p;
}
int countNum (Node *head, int key) {
int count=0;
if (head==nullptr)
return 0;
Node *follow=head;
while (follow!=nullptr) {
if(follow->val==key)
count++;
follow=follow->next;
}
cout<<count;
return count;
}
use Node *head = cons(1,cons(2,cons(2,(cons(4,(cons(5,nullptr)))))));
I think you want to return a pointer to the current node instead of the next node. Also I don't think you can do:
Node *head = (1, ptrToNextNode);
Something like this might work:
struct Node *head = malloc(sizeof (struct Node));
head->value = 1;
head->next = cons(2,cons(2,(cons(4,(cons(5,nullptr))))));
...
Node* cons (int x, Node* p)
{
Node *q=new Node;
q->val=x;
q->next=p;
return q;
}