I don't know why my insertion function is not working for the final insertion i.e. for value 5 plus swapping is also not working. Can anybody assist? - singly-linked-list

The problem in my code starts from the final insertion that I have tried in the main() followed by the swapping method. I don't understand why swapping is not working plus the fact that insertion just doesn't work for the last one simply blows my mind. Is anybody there to help me?
```
void LL::insertion(int info,int val) //insertion problem arises in the fifth insertion.
{
if(head==NULL)
{
cout<<"LL is empty!"<<endl;
Node *temp=new Node;
temp->data=val;
temp->next=NULL;
head=temp;
}
else
{
Node *temp=new Node;
temp->data=val;
query=head;
while(query->data!=info && query->next!=NULL)
{
query=query->next;
}
if(query->data==info)
{
temp->next=query->next;
query->next=temp;
}
else
{
cout<<"The value you entered is not found in the LL!"<<endl;
}
}
}
void LL::swapping(int info,int val) //swapping is not working.
{
if(head==NULL)
{
cout<<"LL is empty!"<<endl;
}
else
{
query=head;
Node *temp;
temp=query;
while(query->data!=info && temp->data!=val)
{
query=query->next;
temp=temp->next;
}
Node *temp1;
temp1=query;
query->next=temp->next;enter code here
temp->next=temp1->next;
delete temp1;
}
}
int main()
{
LL obj; //"obj" is object of of the class "LL"
//cout<<obj.emptiness()<<endl;
obj.insertion(0,1);
obj.insertion(1,2);
obj.insertion(2,3);
obj.insertion(3,4);
obj.insertion(4,5); //here problem arises.
obj.swapping(1,5); //no error is shown on compiler.
}
```

Related

everyone, i have changed my code now i'm making linked list using functions it is successfully build but not printing anything, plz tell my mistake

#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
};
class LinkedList{
Node *head;
public:
//Node *head;
LinkedList(){
head=NULL;
}
void addAtTail(int);
void print();
};
void LinkedList::addAtTail(int val){
Node *nodeToAdd=new Node();
nodeToAdd->data=val;
if(head==NULL){
head=nodeToAdd;
}
else{
Node *temp=head;
while(temp!=NULL){
temp=temp->next;
}
temp->next=nodeToAdd;
}
}
void LinkedList::print(){
Node *temp=head;
while(temp->next!=NULL){
cout<<temp->data;
temp=temp->next;
}
}
int main()
{
LinkedList ll;
ll.addAtTail(10);
ll.addAtTail(20);
ll.addAtTail(30);
ll.print();
cout<<"Hello World";
return 0;
}
i have tried to make linked list by splitting it in functions. It is build successfully but not printing anything can anyone tell me my mistake. Firstly in this post i tried to delete a node which was not in functions now i have another doubt a snow i'm making linked list using functions .
For starters your code does not distinguish the position equal to 0 and the position equal to 1 because for the both positions this while loop
while(i<pos-1){
curNode=curNode->next;
i++;
}
will not be executed.
Also within the loop you are not checking whether curNode becomes equal to a null pointer.
This statement
curNode->next=curNode->next->next;
also can invoke undefined behavior in case when curNode->next is a null pointer.
And the removed from the list node should be deleted using the operator delete. Otherwise there will be a memory leak.
You could rewrite this code snippet for example the following way
else{
cout<<"Enter Position - ";
cin>>pos;
if ( pos < 0 )
{
std::cout << "Invalid position.\n";
}
else
{
Node **curNode = &head;
while ( *curNode && pos-- )
{
curNode = &( *curNode )->next;
}
if ( *curNode == nullptr )
{
std::cout << "Invalid position.\n";
}
else
{
Node *tmp = *curNode;
*curNode = ( *curNode )->next;
delete tmp;
}
}
break;
}
Pay attention to that other parts of the program that deal with positions also can invoke undefined behavior or produce a memory leak and should be rewritten.
Also it would be much better if you will split your program into separate functions.
while inserting the node, you are making temp=NULL and then NULL->next=nodeToAdd which would give an error
so make the while condition as while(temp->next!=NULL)
Incase of printing you are not going till the last node, for this change the while condition to while(temp!=NULL)
void LinkedList::addAtTail(int val){
Node *nodeToAdd=new Node();
nodeToAdd->data=val;
if(head==NULL){
head=nodeToAdd;
}
else{
Node *temp=head;
while(**temp->next!=NULL**){
temp=temp->next;
}
temp->next=nodeToAdd;
}
}
void LinkedList::print(){
Node *temp=head;
while(**temp!=NULL**){
cout<<temp->data;
temp=temp->next;
}
}

Getting Wrong Answer in linked list palindrome

I have written a code in c++ to check whether the linked list is palindrome on not. The code is given below.
Every time I am running the program i am getting the value returned as 1 . In the given example i am using non palindrome string then also i am getting the same answer that its a palindrome.
I have used the c++ standard template library to execute this code
#include<iostream>
#include<stack>
using namespace std;
struct node{
char data;
node *next;
};
void push(struct node** head,char data)
{
struct node *newnode= new node;
newnode->data=data;
newnode->next=(*head);
(*head)=newnode;
}
void print(struct node *ptr)
{
while(ptr!=NULL)
{
cout<<" " <<ptr->data;
ptr=ptr->next;
}
}
//this is the function to check palindrome
int checkpalindrome(node *head)
{
stack<char>s;
node *current=head;
while(current!=NULL)
{
s.push(current->data);
current=current->next;
}
while(current!=NULL && !s.empty() )
{
int ele=s.top();
s.pop();
if(ele==current->data)
current=current->next;
else
{
return 0;
break;
}
}
}
int main(){
node *first=NULL;
push(&first,'a');
push(&first,'b');
push(&first,'b');
push(&first,'d');
int c=checkpalindrome(first);
if(c==0){cout<<"not a palindrome";
}
else
{cout<<"its a palindrome";
}
}
There is no syntax error . Please tell me the logic error in my code
You need to reset current to point to the head, the 2nd while loop never executes in the palindrome function because it is NULL at that point.
// ...
*current = head; // RESET current
while(current!=NULL && !s.empty())
{
// ...
}
// ...

segmentation fault while inserting node at specified position of singly linked list using c++

It works well when I insert node at 0th position,but not when I insert somewhere in the middle .I have kept pointer prev to traverse till the previous node of target position and i have also checked if the node is to be inserted at the tail position. I have no idea why it is giving segmentation fault .Can anyone help me out in solving this problem?
code is:
Node* InsertNth(Node *head, int data, int position)
{
Node * temp=new Node;
int i=1;
temp->data=data;
temp->next=NULL;
Node * prev;
if(position==0)
{if(head==NULL)
head=temp;
else
{
temp->next=head;
head=temp;
}
}
else
{
prev=head;
while(i!=position)
{
i++;
prev=prev->next;
}
if(prev->next=NULL)
{
prev->next=temp;
}
else
{
temp->next=prev->next;
prev->next=temp;
}
}
return head;
}
Without a Minimal, Complete, and Verifiable example nobody can really help you. Nevertheless, this sticks out in a major way:
if(prev->next=NULL) {
prev->next=temp;
}
You assign NULL to prev->next instead of comparing it with ==.
I doubt below code :
while(i!=position)
{
i++;
prev=prev->next;
}
You should modify condition like this
while(prev && i!=position)
{
i++;
prev=prev->next;
}

How do we display a linked list?

So I created the following bit of code but the display function is giving me problems. It breaks into an infinite loop each time I try using it. Could someone please have a look at it and tell me what's going wrong ?
#include<iostream.h>
#include<conio.h>
struct node{
int info;
node *next;
}*ptr,*start,*temp;
node* create_new()
{
ptr=new node;
cout<<"\nEnter the data: ";
cin>>ptr->info;
ptr->next=NULL;
return ptr;
}
void insert_at_beg()
{
ptr=create_new();
if(start==NULL)
{
start=ptr;
}
if(start!=NULL)
{
ptr->next=start;
start=ptr;
}
}
void display()
{
temp=start;
while(temp->next!=NULL)
{
cout<<"\t"<<temp->info;
temp=temp->next;
}
}
void insert_at_end()
{
if(start==NULL)
{
start=ptr;
}
if(start!=NULL)
{
ptr=create_new();
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
}
}
void delete_from_end()
{
if(start==NULL)
{
cout<<"NULL LL";
}
else
{
temp=start;
while(temp->next!=NULL)
{
ptr=temp;
temp=temp->next;
}
ptr->next=NULL;
delete temp;
}
}
void delete_from_beg()
{
if(start==NULL)
cout<<"\nNULL LL";
else
start=start->next;
}
void delete_from_mid()
{
int el;
if(start==NULL)
{
cout<<"\nNULL LL";
}
else
{
cout<<"\nEnter element that you want to delete: ";
cin>>el;
temp=start;
while(temp->next!=NULL&&temp->info!=el)
{
ptr=temp;
temp=temp->next;
}
ptr->next=temp->next;
delete temp;
}
}
void main()
{
clrscr();
start=NULL;
temp=NULL;
ptr=NULL;
insert_at_beg();
display();
getch();
}
Your bug is in this code:
void insert_at_beg()
{
ptr=create_new();
if(start==NULL)
{
start=ptr;
}
if(start!=NULL)
{
ptr->next=start;
start=ptr;
}
}
The first time in start will be null, so you'll do start=ptr. However, now if(start!=NULL) will be true, so you'll do ptr->next=start. Since ptr and start both point to the same thing you'll create an infinite loop.
Firstly I would not recommend you to use global variables especially when you have functions that themselves output parameters of the same type (and value).
The problem according to me is in the function insert_at_beg():
// yes start is NULL initially
if(start==NULL)
{
start=ptr; // now start is not NULL!!
}
//This statement will also be entered.
if(start!=NULL)
{
ptr->next=start;
start=ptr;
}
}
Instead use an else
if(start==NULL)
{
start=ptr; // now start is not NULL!!
}
else
{
ptr->next=start;
start=ptr;
}
}
Also, instead of:
#include<iostream.h>
#include<conio.h>
Use just #include<iostream>
Your bug that cause infinite loop is somewhere else (insert_at_beg(), I saw that someone already added the details so I won't do this too) in the code.
You still have a problem in your code:
void display()
{
temp=start;
while(temp->next!=NULL)
{
cout<<"\t"<<temp->info;
temp=temp->next;
}
}
You will not print the last elemnt. You stop when the next of the current element (temp) is NULL.
Change this to
while(temp) // equivalent to while(temp !=NULL)
Your display function can be simplified:
void display()
{
node * p = start;
while (p != NULL)
{
cout << "\t" << p->info;
p = p->next;
}
cout << endl; // The side effect of this is to print blank line when empty list.
}

Trouble in traversing BST

I started learning about trees and tried writing the code for BST. Unfortunately i am having trouble displaying the tree datas. I am trying to implement Depth-first traversal. But have no idea how to implement it. Below is my code
#include<iostream>
using namespace std;
class node
{
public:
int data;
node *left,*right;
};
class btree
{
private:
node *root;
public:
btree(){root=NULL;}
void insert(int value)
{node *temp=new node;
if(root == NULL)
{
temp->right=NULL;
temp->data=value;
temp->left=NULL;
root=temp;
}
else
insertHelper(root, value);
}
void insertHelper(node* Node, int value)
{
if(value < Node->data)
{
if(Node->left == NULL)
{
Node->left=new node;
Node->left->data=value;
Node->left->left=NULL;
Node->left->right=NULL;
}
else
insertHelper(Node->left, value);
}
else
{
if(Node->right== NULL)
{
Node->right = new node;
Node->right->data=value;
Node->right->left=NULL;
Node->right->right=NULL;
}
else
insertHelper(Node->right, value);
}
}
void disp()
{node*tmp=root;
if(tmp==NULL)
cout<<"empty"<<endl;
else
{
cout<<tmp->data<<endl;
disphelper(tmp);
}
}
void disphelper(node *tmp)
{
if(tmp->left!=NULL)
{
cout<<tmp->left->data<<endl;
tmp=tmp->left;
disphelper(tmp);}
if(tmp->right!=NULL)
{
cout<<tmp->right->data<<endl;
tmp=tmp->right;
disphelper(tmp);
}
}
};
int main()
{
btree binarytree;
binarytree.disp();
binarytree.insert(10);
binarytree.insert(5);
binarytree.insert(30);
binarytree.disp();
}
the output is
empty
10
5
Can anyone please tell me why 30 is not displayed?
MODIFY your code to
void disphelper(node *tmp)
{
if(tmp == NULL)
return;
cout<<tmp->data<<endl; // print data for current node
if(tmp->left!=NULL) // traverse left branch
{
//cout<<tmp->left->data<<endl;
//tmp=tmp->left;
disphelper(tmp->left);}
if(tmp->right!=NULL) // traverse right branch
{
//cout<<tmp->right->data<<endl;
//tmp=tmp->right;
disphelper(tmp->right);
}
}
And it should work.
void disp()
{node*tmp=root;
if(tmp==NULL)
cout<<"empty"<<endl;
else
{
disphelper(tmp);
}
}
The reason you're not getting any output here is that in disphelper() you are first checking whether the left node is NULL and then changing it when you recurse into it. Same when you recurse into the right node.
void disphelper(node *tmp)
{
if(tmp->left!=NULL)
{
cout<<tmp->left->data<<endl;
//tmp=tmp->left; // Get rid of this.
disphelper(tmp->left); // Use this.
}
if(tmp->right!=NULL)
{
cout<<tmp->right->data<<endl;
//tmp=tmp->right; // Get rid of this
disphelper(tmp->right); // Use this.
}
}
Instead of changing the value of temp, which should be the same for both comparisons, just pass the left or right node in.
Two other things. Firstly, you're leaking memory like mad here: In your insert(), you create a new object every time, but only use it the first time, every other time it leaks. Your node class should be taking care of memory by having a destructor which deletes both nodes.
Secondly, before you post code, could you please take the trouble to format it so that the indentation is consistent? It's not the pain it use to be to do this - a lot of editors will do it for you or you can use the excellent Astyle. I know it's a small point but it's irritating for those who read your code - including, presumably the guy who's going to mark you homework! Thanks :-)