#include<stdio.h>
#include<conio.h>
#include<windows.h>
struct node
{
int a;
struct node *next;
};
void createlist(struct node **head)
{
struct node *p,*temp;
int n;
printf("enter the number\n");
scanf("%d",&n);
p=(struct node*)malloc(sizeof(struct node));
p->a=n;
if(*head==0) {
*head=p;
p->next=0;
temp=p;
}
else {
temp->next=p;
temp=p;
p->next=0;
}
}
void frontbacksplit(struct node **head,struct node **head1,struct node **head2)
{
int counter=0,i;
struct node *temp,*p;
temp=*head;
while(temp!=0) {
counter++;
temp=temp->next;
}
int n;
if(counter%2==0) {
n=counter/2;
} else {
n=(counter+1)/2;
}
temp=*head;
for(i=0;i<n-1;i++) {
if(*head1==0) {
*head1=temp;
}
temp=temp->next;
}
p=temp;
temp=temp->next;
p->next=0;
for(i=n+1;i<counter;i++) {
if(*head2==0) {
*head2=temp;
}
temp=temp->next;
}
}
void display(struct node **head)
{
struct node *temp;
temp=*head;
while(temp!=0) {
printf("%d\t",temp->a);
temp=temp->next;
}
printf("\n");
}
int main()
{
int n=1,i,k;
struct node *head3,*head1,*head2;
head3=0;
head1=0;
head2=0;
while(n==1) {
printf("enter \n1-To add the elements\n2-To split the list into front and the back\n3-To display the elements\n");
scanf("%d",&i);
switch(i)
{
case 1:
createlist(&head3);
break;
case 2:
frontbacksplit(&head3,&head1,&head2);
break;
case 3:
printf("enter\n1-To display front list\n2-To display rear list\n");
scanf("%d",&k);
switch(k)
{
case 1:
display(&head1);
break;
case 2:
display(&head2);
}
break;
default:
printf("please enter a valid option\n");
}
printf("enter\n1-To continue\nany other number to exit\n");
scanf("%d",&n);
}
getch();
return 0;
}
I have written this code for front / back splitting of the linked list. For example if the list is [1 2 3 4 5] then this program splits the list into the two lists: front part (1 2 3) and back part(4 5), if the number of elements are equal both the parts get equal number of elements.
Problem: When I try to add elements in the source list, the first elements get added as usual but when I try add other element my program shows a run time error. I think there is problem with the pointer variable temp but almost same code for the creation of linked list worked properly.
I am using dev c++ ide on windows 8.
Of course point out if you did't like the way this question is asked, as this is my first time.
On first look this line temp->next = p in createlist function is wrong, temp is a local variable, although you make it point to the element when the list is created for the first time the value is lost after the createlist function returns, so will you be accessing junk addresses in consecutive calls to createlist
The pointer variable 'temp' in createlist() function is being used without assignment on calls subsequent to the first call. You could benefit using -Wall options if you are using GCC.
Maybe you should change to this:
void createlist(struct node **head)
{
struct node *p,*temp;
int n;
printf("enter the number\n");
while(scanf("%d",&n) != EOF)
{
p=(struct node*)malloc(sizeof(struct node));
p->a=n;
if(*head==0)
{
*head=p;
p->next=0;
temp=p;
}
else
{
temp->next=p;
temp=p;
p->next=0;
}
}
}
Related
#include <iostream>
using namespace std;
struct node
{
int a;
node *next=NULL;
void insert()
{
cout<<"\n"<<"insert a value ";
cin>>a;
}
void show()
{
cout<<"value inserted is ";
cout<<a;
}
};
Insertion is working fine(addele func is fine)
void addele(node *head)
{
node *curr = head;
node n;
while(!(curr->next==NULL))
{
curr=curr->next;
}
curr->next=&n;
n.insert();
n.show();
}
The problem is, although my code is right for the display function but I am getting infinte zeros after running the code
void display(node *head)
{
node *curr = head;
while(!(curr->next==NULL))
{
cout<<curr->a;
curr=curr->next;
}
}
int main()
{
int ch;
node n,*h;
h=&n;
while (1)
{
cout<<" 1. Add Element \n";
cout<<" 2. Display list \n";
cout<<" 3. Exit \n";
cin>>ch;
switch (ch)
{
case 1:addele(h);
break;
case 2:display(h);
break;
}
if (ch==3)
{
return 0;
}
}
return 0 ;
}
-Basically, if i insert any number for eg. 1 2 in linked list
-The desired output after calling display function should be 2 1
-But the program ends in never ending program with infinite zeros
Can any one help me with this ?
I m attaching the output also...
So I've been trying to write a code of various operations on 2 linked lists using functions and while the lists are being created properly and insertion and deletion is taking place correctly at all positions but inserting at the head condition seems to be not working.
I tried creating an LL using this function:
void Create(struct node **head) {
if (No_of_List==2)
{
cout<<"\nCan't create more lists\n";
Operations();
}
int n;
cout<<"Create a linked list.\n\nEnter the number of elements in the Linked List: ";
cin>>n;
if (n!=0)
{
No_of_List++;
}
LIST_SIZE=n;
while(n--)
{
cout<<"Enter the value to be inserted: ";
node *new_node= new node;
cin>>new_node->data;
new_node->next=0;
if(Empty_List(*head)==1)
*head=new_node;
else
{
temp=*head;
while (temp->next!=NULL)
temp=temp->next;
temp->next=new_node;
}
}
Operations();
}
and my insertion code is:
node *new_node = new node;
cout<<"Enter the value to be inserted: ";
cin>>new_node->data;
new_node->next=NULL;
int index;
cout<<"Enter the index: ";
cin>>index;
if (index==0) // CONDITION NOT WORKING
{
new_node->next=head;
head=new_node;
cout<<"Value inserted successfully.\n";
LIST_SIZE++;
goto l;
return;
}
if (index>LIST_SIZE)
{
cout<<"Invalid index.";
goto l;
return;
}
temp=head;
temp1=NULL;
if (Empty_List(head)==1)
{
cout<<"\nLinked List empty.\n";
}
for (int i=0;i<index;i++)
{
temp1=temp;
temp=temp->next;
}
temp1->next=new_node;
new_node->next=temp;
cout<<"Value inserted successfully.\n";
LIST_SIZE++;
}
but my index=0 condition doesnt insert any value at the head whereas the other value is inserted at other index places. Pls help
**Note: ** this is a code snippet only. you can ask for the full code to find any other errors but it's a long one so I didnt insert it here
https://onlinegdb.com/r1UzIfzPD Here's the full code
Why is the argument for display in main() start and not newptr? Also, how does np->next=save; and np=np->next work in their respective functions? I am very new to the concept of linked lists. Any help would be much appreciated.
#include<iostream>
using namespace::std;
struct node
{
int info;
node *next;
} *start,*newptr,*save,*ptr;
node * create_new_Node(int);
void insert_beg(node *);
void display(node*);
int main()
{
start=NULL;
int inf; char ch='y';
while(ch=='y'||ch=='Y')
{
system("cls");
cout<<"Enter information for the new node : \n";
cin>>inf;
cout<<"\nCreating new node";
system("pause");
newptr=create_new_Node(inf);
if(newptr!=NULL)
{
cout<<"New node created successfully.";
system("pause");
}
else
{
cout<<"\aNot enough memory =S ...\n";
exit(1);
}
cout<<"Now inserting this node to the beginning of the list :";
system("pause");
insert_beg(newptr);
cout<<"Now the list is : ";
display(start);
cout<<"Press Y or y to enter more nodes :::: ";
cin>>ch;
}
return 0;
}
node * create_new_Node(int n)
{
ptr=new node;
ptr->info=n;
ptr->next=NULL;
return ptr;
}
void insert_beg(node *np)
{
if(start==NULL)
{
start=np;
}
else
{
save=start;
start=np;
np->next=save;
}
}
void display(node * np)
{
while(np!=NULL)
{
cout<<np->info<<" -> ";
np=np->next;
}
}
in insert_beg, the pointer to start is changed to the new start position which is the newly inserted node.
in my opinion, pointer operations are better to undrstand in a graphical model..
Why is the argument for display in main() start and not newptr?
Because start is the head pointer in your linked list and always points to the first node in the linked list. To display the linked list, you have to start from the first node and that first node is pointed to by start pointer.
how does np->next=save; and np=np->next work in their respective
functions?
np->next=save; it means that next pointer of node np should point to the node which is pointed to by save pointer.
np=np->next; it is being used in display function to iterate over your linked list.
I'm trying to print all the elements of the list, but I'm getting a wrong output.
The code gets 2, 0 and 10, and when I call the procedure "travel_in" it only shows 0, 2.
And have some doubts with my del_start(), it deletes the 0 and not the 2..
What I'm doing wrong?
Compiled in Windows 64bits with Cygwin
Output
2 0 10 0 2
Here is the code
# include < iostream >
# include < stdio.h >
using namespace std;
template <class clali>
class double_list
{
protected:
clali node1;
clali *listad;
public:
double_list()//constructor
{
listad=NULL;
}
void insert_strt(clali node1)
{
clali *temp;
temp=new clali;
*temp=node1;
//check if list is not empty
if (listad==NULL)
{
listad=temp;
listad->next=NULL;
listad->before=NULL;
}
else
{
temp->next=listad;
listad->before=temp;
temp->before=NULL;
listad=temp;
}
}
int vertam()
{
int res=0;
clali *temp;
temp=listad;
if (temp==NULL)
{
cout<<"Empty list!"<<endl;
res=0;
}
else
while(temp!=NULL)
{
res++;
temp=temp->next;
}
return res;
}
void insert_mid(clali node1, int pos)
{
int i;
clali *temp,*temp2;
temp2=new clali;
temp=listad;
if(pos<vertam)
{
for(i=1;i<pos;i++)
temp=temp->next;
*temp2=node1;
temp2->next=temp->next;
temp->before=listad;
temp->next=temp2;
}
else
cout<<"Cant show the data!"<<endl;
}
clali del_start()
{
clali a,*temp;
a=*listad;
temp=listad;
listad=listad->next;
delete temp;
return a;
}
void insert_end(clali node1)
{
clali *temp,*temp2;
temp=listad;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp2=new clali;
*temp2=node1;
temp->next=temp2;
temp2->before=temp;
temp2->next=NULL;
}
clali clear_end()
{
clali b,*temp,*temp2;
int j=1;
temp=listad;
do
{
temp=temp->next;
cout<<"Element : "<<j<<endl;
j++;
}while(temp->next!=NULL);
b=*temp;
temp2=temp->before;
temp2->next=NULL;
// delete temp;
return b;
}
void travel_in()
{
clali *temp;
temp=listad;
while(temp->next!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
};
struct integer
{
int data;
integer*next,*before;
};
typedef struct integer Integer;
int main()
{
Integer node;
node.next=NULL;
node.before=NULL;
double_list<Integer> test_list;
test_list.insert_strt(node);
node.data=2;
cout<<node.data<<endl;
test_list.insert_end(node);
node.data=0;
cout<<node.data<<endl;
test_list.insert_end(node);
node.data=10;
cout<<node.data<<endl;
test_list.del_start();
test_list.travel_in();
}
I see at least one obvious bug. Initial analysis indicates that the listad class member is the pointer to the first element in the doubly-linked list. In that case, the following is obviously wrong (reformated for legibility, please indent your code correctly):
void insert_mid(clali node1, int pos)
{
int i;
clali *temp,*temp2;
temp2=new clali;
The purpose of this class method is, apparently, to insert the new node in the middle of the linked list.
temp2 is the new node.
temp=listad;
if(pos<vertam)
{
for(i=1;i<pos;i++)
temp=temp->next;
temp appears to be the insert position in the middle of the list.
temp->before=listad;
For some unclear reason this code attempts to set the before pointer of an existing node in the middle of the list to the head of the list. This makes no sense, and is wrong.
Let's go step by step in main().
When you first call insert_strt() the argument node has garbage value for member data. So an Integer object with some garbage value for data gets inserted at the start of test_list. Then you insert Integer objects with data 2 and 0, respectively, at the end of the list.
Later, you delete the first clali object from test_list which deletes the object with garbage value in its data field. So, after deletion, you have objects with data value 2, and 0 in the list in that order.
At the end, you print the list with travel_in() but it does not do what you think it does. What it is actually doing is that if the list has at least one element then it prints all but the last element in the list. If the list is empty, it will cause a segmentation fault (in the condition of while loop as temp would be NULL). So it will print: 2 (but your list has 2 and 0).
You can write travel_in() as follows.
void travel_in()
{
clali *temp = listad;
while(temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
By the way, comment/remove the cout statements in the main() function. They may confuse you.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been learning the implementation of single linked list in c++.
Thing is that I understood the concept behind single linked list but I am not able to guess where I have done mistake in the code.
Whenever I insert a new node, it takes the first position (i.e head) and the size of the list is always 1.
I tried to solve it but sometimes display function turns into infinite loop.
I am getting no clue on this.
Its been pricking my mind for a week.
All I can guess is, I am not referencing the addresses properly in the code.
Am I messing up with the pointers? Help by making me understand the mistake I have done.Thank you.
SLLCLAS.CPP
#include<iostream>
#include<conio.h>
class node{
public:
int data;
node *next;
};
class sll{
private:
node *head;
public:
ssl(){
head=NULL;
}
void display();
void insert(int,int);
};
void sll::display(){
if(head==NULL){
cout<<"List is Empty";
}else{
cout<<"\n";
for(node *t=head;t!=NULL;t=t->next){
cout<<t->data<<"->";
}
cout<<"\n";
}
void sll::insert(int position,int data){
node *temp=new node();
temp->data=data;
if(position<0){
cout<<"\nPosition not valid";
}else if(head==NULL || position==1){
temp->next=head;
head=temp;
}else{
node *p,*q;
q=head;
int count=1;
while(count<position && q!=NULL){
count++;
cout<<"\nCount:"<<count;
p=q;
q=q->next;
}
p->next=temp;
temp->next=q;
delete(temp);
}
int main(){
clrscr();
sll list;
int ch,val,pos;
do{
cout<<"\nSINGLY LINKED LIST\n1: Insert\n2: Delete\n3: Display\n Enter your choice:";
cin>>ch;
switch(ch){
case 1:
cout<<"\nEnter the position:";
cin>>pos;
cout<<"\nEnter the value:";
cin>>val;
list.insert(pos,val);
list.display();
break;
case 2:
break;
case 3:
list.display();
break;
default:
cout<<"\nWrong choice";
}
cout<<"\nDo you want to continue(1/0):";
cin>>ch;
}while(ch!=0);
getch();
}
EDIT:
I am running the code on Turbo C++ Version 3.0 on windows 8.1 64bit
using dosbox.
This is a fixed version of the function insert:
void sll::insert(int position, int data) {
node* temp = new node();
temp->data = data;
if (position <= 0) {
cout << "\nPosition not valid";
} else if (head == NULL || position == 1) {
temp->next = head;
head = temp; // ---------------------- problem here
} else {
node* p, *q;
q = head;
int count = 1;
while (count < position && q != NULL) {
count++;
cout << "\nCount:" << count;
p = q;
q = q->next;
}
p->next = temp;
temp->next = q;
}
//delete (temp); //<---------------- problem here
}
You create a node to insert in the list but at the end of the function deleted (with pointer referencing to this memory address), when accessing the memory deleted anything could happen.
The other problem would give you compiler error you are assigning a node variable to a node* variable, with what compiler you are testing.
The are other problems as #include <iostream.h>, iostream is a header from C++ that don't have extension (ex: #include <vector> or #include <iostream>).
The main function it's not standart, changed to int main() if the parameters are not used or int main(int argc, char* argv[]) if they are. You would need to return and integer from main function.
I don't have clrscr(); function defined, probably platform dependent (i am testing with MinGW GCC 4.9.0 with C++11 in Windows).
The statement
delete(temp);
is highly suspicious in the insert function.
Basically temp reference the new node you take care to create and setup. But you delete it before exiting the function. After the first insert, you are manipulating freed memory.
The statement
head=*temp;
make no sense. head is a node*, and you are assigning a node value. If it ever compiles, head is also containing garbage value.
#include <iostream>
using namespace std;
struct node
{
int info;
node *next;
};
class DS
{
private:
node *temp;
node *temp1;
node *head;
int key;
int x;
public:
DS()
{
head=temp=temp1=NULL;
}
void insert()
{
for (int i=0; i<1; i--)
{
cout<<"Enter 0 to stop and 1 to continue:";
cin>>x;
cout<<endl;
if (x==1)
{
if (head==NULL)
{
head=new node;
cout<<"Enter the value in head's Info";
cin>>head->info;
cout<<endl;
head->next=NULL;
}
cout<<"Enter the number after which you want to add node:";
cin>>key;
cout<<endl;
temp=head;
while (temp!=NULL)
{
if (temp->info==key)
{
temp1=new node;
cout<<"Enter value in new node:";
cin>>temp1->info;
cout<<endl;
temp1->next=temp->next;
temp->next=temp1;
}
temp=temp->next;
}
}
else break;
}
}
void Del()
{
temp=head;
if(head==NULL)
return;
cout<<"Enter the number after which you want to delete the node:";
cin>>key;
cout<<endl;
while( temp!=NULL)
{
if (temp->next->info==key)
{
temp1=temp->next;
temp->next=temp->next->next;
delete temp1;
break;
}
temp=temp->next;
}
}
void searching()
{
temp=head;
cout<<"Enter key to found node:";
cin>>key;
cout<<endl;
while (temp!=NULL)
{
if (temp->info==key)
{
cout<<"Node found"<<endl;
break;
}
temp=temp->next;
}
}
void printing()
{
temp=head;
while (temp!=NULL)
{
cout<<endl;
cout<<temp->info<<endl;
temp=temp->next;
}
}
void emptiness()
{
temp=head;
if (temp->next==NULL)
{
cout<<"Empty list";
cout<<endl;
}
else if (temp!=NULL)
cout<<"Not empty";
}
};
int main()
{
DS obj;
obj.insert();
cout<<endl;
obj.Del();
cout<<endl;
obj.searching();
cout<<endl;
obj.printing();
cout<<endl;
obj.emptiness();
return 0;
}