I want to know what is the problem in creat_list2 function..
I have a problem in this code and as i knew it's in the creat_list2 cause the program run Successfully
when i stop this function it ask the user to enter a numbers that will be stored in the list 1 then print them but the problem as i saw is in the second fuction that creat the second list...,I have to submit my assignment tomorrow so I wish if any body can help me to solve this problem.
#include<iostream>
using namespace std;
struct node{
int x;
node *next;
};
struct snode{
int y;
snode *next;
};
creat_list1(node *&head, node *&tail)
{
int num;
cout<<"enter number\n";
cin>>num;
while(num!=0)
{
node *np=new node;
np->x=num;
if(head==nullptr)
head=np;
else
tail->next=np;
tail=np;
tail->next=nullptr;
cout<<"enter number again\n";
cin>>num;
}
}
creat_list2(node *&head, snode *shead, snode *stail)
{
int sum=0;
while(head!=nullptr)
{
for(int i=0;i<head->x;i++)
sum+=i;
snode *np= new snode;
np->y=sum;
if(head==0)
shead=np;
else
stail->next=np;
stail=np;
stail->next=nullptr;
}
head=head->next;
}
void print_list1 (node *head)
{
while(head!=nullptr)
{
cout<<head->x<<"\t";
head=head->next;
}
}
void print_list2(snode *shead)
{
while(shead!=nullptr)
{
cout<<shead->y<<"\t";
shead=shead->next;
}
}
main()
{
node *head=nullptr, *tail=nullptr;
snode *shead=nullptr, *stail=nullptr;
creat_list1(head,tail);
creat_list2(head,shead,stail);`enter code here`
print_list1(head);
print_list2(shead);
}
There are couple of issues with yours code,
creat_list2(node *&head, snode *shead, snode *stail) if u updated
head like head=head->next; it will reflect at the main.
shead and stail are just a local pointer and any update to just a pointer like stail=np;will not have any changes at the `main
There seems to be typo if(head==0) shead=np; instead it should be
if(shead==0) shead=np; which is causing null pointer exception.
I tried to fix the error at creat_list2 but functionality is still ambiguous to me,
void creat_list2(const node *head, node *&shead, node *&stail) //updated in argument
{
int sum = 0;
while (head != nullptr)
{
//for (int i = 0; i < head->x; i++)
// sum += i;
node *np = new node;
np->x = sum;
if (shead == 0) //error : head instead shead
shead = np;
else
stail->next = np;
stail = np;
stail->next = nullptr;
head = head->next;
}
}
Related
I have tried to implement queue using linked list. This is the code i wrote. When i try to use the disp() method i get a infinite loop running. I am not able to find the error in the logic. I fail to understand how the line while(temp!=NULL) and incrementing the temp never ends.
#include<iostream>
using namespace std;
struct node{
int x;
node *next;
};
class queue{
node *front,*rear;
public:
queue(){
front = NULL;
rear= NULL;
}
void enqueue(int x){
node *temp=new node;
temp->x=x;
temp->next=NULL;
if(rear==NULL){
rear=temp;
front = temp;
}
else{
rear->next=temp;
rear=temp;
}
}
int dequeue(){
node *temp =front;
if(temp!=NULL){
int x =temp->x;
temp=temp->next;
delete temp;
return x;
}
else{
return -1e7;
}
}
void disp(){
node *temp=front;
while(temp!=NULL){
cout<<temp->x<<" ";
temp=temp->next;
}
}
};
int main(){
int n;
cin>>n;
queue obj;
for(int i=0;i<n;i++){
int x;
cin>>x;
obj.enqueue(x);
}
int x,y;
cin>>x>>y;
obj.enqueue(x);
obj.enqueue(y);
obj.dequeue();
obj.disp();
}
Your dequeue is not properly dequeueing the first element:
node *temp =front;
if(temp!=NULL){
int x =temp->x;
temp=temp->next;
delete temp;
return x;
}
temp = temp->next makes temp point to the second node and in the next line you delete that second node, instead of the first one.
Make the second node the new front and delete the old front:
node *temp = front;
if(temp != NULL){
int x = temp->x;
front = temp->next; // <---
delete temp;
return x;
}
this is the code
#include <iostream>
using namespace std;
struct Node{
int data;
Node *next;
};
Node *head;
`insert function takes a number as argument`
void insert(int a)
{
Node *temp = new Node();
temp -> data= a;
temp->next = head;
head = temp;
}
void print(void)
{
Node *temp1;
temp1 = head;
while(head != NULL)
{
cout<<temp1->data<<endl;
temp1 = temp1->next;
}
}
**main function**
int main()
{
head = NULL;
int a;
int b;
cout<<"how many elements do you want to insert";
cin>>b;
for (int i = 0;i < b; i++)
{
cout<<"enter a number"<<endl;
cin>>a;
insert(a);
print();
}
return 0;
}
when I enter the number to insert it shows program has stopped working. I am trying to insert numbers to linked list and print it ever time I add a number.I have checked for many other errors but it has none.
Looks like it might be due to an infinite loop like one of the comments says. Try updating the loop in the print function like this:
void print() {
Node *temp1;
temp1 = head;
// Here, I switched `head` with `temp1`
while (temp1 != nullptr) {
std::cout << temp1->data << std::endl;
temp1 = temp1->next;
}
}
#include <iostream>
using namespace std;
int main()
{
struct node
{
int data;
node * next;
};
node * head;
node * n;
node * temp;
node * q;
int number;
cout << "Enter numbers";
cin >> number;
n = new node;
n->data = number;
head = n;
temp = n;
while (cin >> number)
{
while (number != -500)
{
n = new node;
n->data = number;
temp->next = n;
temp = n;
}
}
while (head != NULL)
{
cout << head->data;
head = head->next;
}
}
I don't understand why this would not work. The program creates a new node then sets whatever the user entered equivalent to the variable data of that new node then it makes head and temp point to the new node. Then it gets the users second input and compares it to -500 and if it evaluates as true it creates a new node puts the data of the second input into the variable data then it links the first node and second node together then it makes temp point to the second node. If the condition of the 2nd while loop is false it goes to the third which is where it is suppose to print the list.
Who sets the last node's next to NULL?
At n = new node; n->next is not NULL but undefined, in Debug versions usually it is 0xcccccccc or something similar value to make it visible that it is not initialized. If you try to dereference it, you will get an access violation.
while (cin >> number) { // this loop is endless, because you can always read the user input data (unless some exception happen)
while (number != -500)
{
n = new node; // you already have data allocated. no need to allocate it once more
n->data = number;
temp->next = n;
temp = n;
// as was already mentioned: set n->next to NULL
} }
if you want to break after you checked that the number is not -500, then you can do the following instead:
while (cin >> number) {
if (number != -500) { ...; // do your stuff
break;
}
}
And, by the way, you have a memory leak. If you use flat C pointers then consider delete operator to clear your memory. For that purpose, you need to know where your list starts(basically, head) and iterate through a whole list invoking delete node.
Please, also consider, that it is a bad code style to write something like:
while (cin >> number)
You can also try this-
This code makes a linked list on user input and printlinkedlist (function) print the linked list created.
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
node* next;
};
void printlinkedlist(node* node)
{
int c=0; //taken just for good looking output
while(node!=NULL)
{
if(c>0)
{
cout<<"->"<<node->data;
node = node->next;
}
else
{
cout<<node->data;
node = node->next;
c++;
}
}
}
int main() {
int n;
cout<<"Enter no. of nodes=";
cin>>n; //User enters number of nodes he want.
int num,c=0; //initialized c for setting head with second node..
node* head = new node; //initialized head node
node * temp = new node; //initialized temp node
cin>>num;
head->data=num;
for(int i=2;i<=n;i++)
{
if(c==0)
{
cin>>num;
temp->data=num;
head->next=temp; //head point to second node i.e. temp
c++;
}
else
{
cin>>num;
node * temp1 = new node; //initialize other temp node for every value
temp1->data=num;
temp->next=temp1; //point to temp1 to temp
temp=temp1; //set temp as temp1
}
}
printlinkedlist(head);
}
#include<iostream>
using namespace std;
class node{
public:
int data;
node* next;
};
// a function to create linked list passing pointer to pinter
void create_list(node**head)
{
int num;//num is the data
cin>>num ;
node*new_node=new node();//
new_node->data=num;
new_node->next=NULL;
node*temp;
if(*head==NULL)
{
*head=temp=new_node;
}
else{
temp->next=new_node;
temp=new_node;
}
}
void print_list(node* head)
{
if(head == NULL)
{
cout<<"empty list"<<endl;
}
node *ptr = NULL;
ptr=head;
cout<<"data in the list: "<<endl;
while(ptr!=0)
{
cout<<ptr->data<<endl;
ptr=ptr->next;
}
}
int main()
{
int n,i; //
cout<<"enter the number of nodes:"<<endl;
cin>>n;
cout<<"enter data as num:"<<endl;
node* head=NULL;
for(i=0;i<n;i++)
{
create_list(&head);//passing the address of head
}
print_list(head);
return 0;
}
I have Linked List code, the Copy_List function crashes the program and won't work: it gives no syntax error so it's logical. I'm not sure where the exact problem lies, so any help would be appreciated.
Here is the code:
#include <iostream>
using namespace std;
struct node{
int info;
node *link;
};
class Linked_List{
private :
int count;
node *first;
node *last;
node *current;
public:
Linked_List() {
count=0;
first=NULL;
last=NULL;
}
void Initialize_List(){
cout<<"Enter Number OF Nodes"<<endl;
cin>>count;
first=last=current=new node;
for(int i =0;i<count;i++){
cout<<"Enter New Node Info :"<<endl;
cin>>current->info;
last->link=current;
last=current;
current=new node;
}
last->link=NULL;
}
bool Is_Empty(){
if(first==NULL)
{
return true;
}
else{
return false;
}
}
int Front () {
if (first != NULL)
return first-> info;
else return 0;
}
int Back () {
if (last != NULL)
return last-> info;
else return 0;
}
void Insert_Last(int x){
count++;
current=new node;
current->info=x;
last->link=current;
last=current;
last->link=NULL;
if(first==NULL)
first=current;
}
void Delete_First(){
if(!Is_Empty()) // Or if(first==NULL)
{
node *p;
p=first;
first=first->link;
delete p;
count --;
if(count==0)
first=last=NULL;
}
}
friend void Copy_List (Linked_List &n,Linked_List &m);
};
void Copy_List (Linked_List &n,Linked_List &m){
Linked_List temp;
while(!n.Is_Empty()){
temp.Insert_Last(n.Front());
n.Delete_First();
}
while (!temp.Is_Empty()) {
n.Insert_Last(temp.Front());
temp.Delete_First();
}
}
void main (){
Linked_List obj,obj2;
cout<<"Is the list empty ?"<<" "<<boolalpha<<obj.Is_Empty(); cout<<endl;
obj.Initialize_List();
cout<<"Is the list empty ?"<<" "<<boolalpha<<obj.Is_Empty(); cout<<endl;
Copy_List (obj,obj2);
}
Suggestions for improvement:
Add a default constructor to node so that it gets initialized properly when constructed.
struct node{
node(int in = 0) : info(in), link(NULL) {}
int info;
node *link;
};
You don't need current as a member of Linked_List. It's useful only in some functions as a function varible.
Implement Initialize_List() using Insert_Last. That keeps the function cleaner. It also avoids redundant code.
void Initialize_List(){
cout<<"Enter Number OF Nodes"<<endl;
int num;
cin>>num;
for(int i =0;i<num;i++){
cout<<"Enter New Node Info :"<<endl;
int info;
cin >> info;
this->Insert_Last(info);
}
}
Insert_Last had assumptions about which is a valid pointer and which is not, which won't be true if you started using to from Initialize_List. It can be simplified to:
void Insert_Last(int x){
count++;
node* current=new node;
current->info=x;
if ( first == NULL )
{
first = last = current;
}
else
{
last->link=current;
last=current;
}
}
Implementation of Copy_List you posted deleted all items from the first argument and put them in the second argument. I am not sure that was the purpose. If you want to keep the contents of the first argument unchanged and want to copy its contents to the second argument, an alternate method is necessary. Here's what I came up with:
void Copy_List (Linked_List &n,Linked_List &m){
Linked_List temp;
node* current = n.first;
for ( ; current != NULL; current = current->link )
{
temp.Insert_Last(current->info);
}
current = temp.first;
for ( ; current != NULL; current = current->link )
{
m.Insert_Last(current->info);
}
}
You don't have a destructor in Linked_List. The default implementation provided by the compiler won't release the memory allocated by the class. In order to deallocate the memory allocated by the class, you need to implement a destructor.
~Linked_List() {
node* current=first;
while ( current != NULL )
{
node* temp = current->link;
delete current;
current = temp;
}
}
In the new list last pointer is not initialized firstly:
void Insert_Last(int x) {
...
last->link=current; // for the new List last should be initialized
last = current;
last->link=NULL;
Supposed change - remove the line last->link=current;
last = current;
last->link=NULL;
I'm trying out a basic program that will randomly initialize a linked list and print the value at a user-specified index (getnth). However, I'm running into a weird segmentation fault that appears when I comment out a specific cout line, and disappears when I uncomment it.
#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int x;
node *next;
};
void ins(struct node*& headRef, int n)
{
node *newNode = new node;
if (!newNode)
return;
newNode->x = n;
if (!headRef)
newNode->next = NULL;
else
newNode->next = headRef;
headRef = newNode;
cout<<"\n"<<n<<" inserted at "<<headRef<<"\n\n";
}
void disp(struct node* head)
{
node *temp = head;
if (!temp)
{
cout<<"\n\nLL empty\n";
return;
}
while (temp)
{
cout<<temp->x<<" ";
temp = temp->next;
}
cout<<"\n\n";
}
void getnth(struct node* head, int n)
{
int i=0;
node *temp = head;
while (temp)
{
if (i == n)
{
cout<<"\n"<<temp->x<<"\n\n";
return;
}
}
cout<<"\nIndex too high\n";
}
int main()
{
node *head;
int i;
srand(time(NULL));
for (i=0; i<10; i++)
{
ins(head, rand()%10+1);
cout<<"Main head is "<<head<<"\n"; // segfault appears if this line is commented out, disappears if it's not
}
cout<<"\nInitial LL\n\n";
disp(head);
cout<<"\nEnter index ";
cin>>i;
getnth(head, i);
return 0;
}
In main initialize
node *head=NULL;
and your getnth is wrong , fix it.
May be something like this :-
void getnth(struct node* head, int n)
{
int i=0;
node *temp = head;
while (temp)
{
if (++i == n)
{
cout<<"\n"<<temp->x<<"\n\n";
return;
}
temp=temp->next;
}
cout<<"\nIndex too high\n";
}
By default, the pointer "head" in "main( )" is initialized with garbage, because it's automatic variable allocated on program stack.
So, when you pass the pointer "head" to the function "disp( )", this pointer is dereferenced and it causes segmentation fault.
You have to initialize the pointer "head" with 0 explicitly, and this will fix the problem.