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.
Related
I have been trying to create a linked list in c++. But only the last element of the linked list is displayed. I have searched for the error but i cannot find it. I have implemented the logic that I learned form c language. All the nodes are connecting properly. But still i cannot find the error.
This logic works on c language.
Please help.
#include<iostream>
using namespace std;
class node{
public:
int data;
node *next;
}*head,*newnode,*temp;
node* getnode();
node* create(int);
void display(node*);
int main()
{
int n;
head=getnode();
cout<<"Enter the no of nodes: ";
cin>>n;
head=create(n);
display(head);
return 0;
}
node *getnode()
{
head=new node();
head->next=nullptr;
return(head);
}
node *create(int n)
{
head=getnode();
cout<<"Enter the value of node 1: ";
cin>>head->data;
temp=getnode();
temp=head;
for(int i=1;i<n;i++)
{
newnode=getnode();
cout<<"Enter the value of node "<<i+1<<": ";
cin>>newnode->data;
newnode->next=nullptr;
temp->next=newnode;
temp=newnode;
}
return(head);
}
void display(node *head)
{
while(head!=nullptr)
{
cout<<"->"<<head->data;
head=head->next;
}
}
#include<iostream>
using namespace std;
class node{
public:
int data;
node *next;
node(int x)
{
data=x;
next=nullptr;
}
}*head,*newnode,*temp;
node* create(int);
void display(node*);
int main()
{
int n;
cout<<"Enter the no of nodes: ";
cin>>n;
head=create(n);
display(head);
return 0;
}
node *create(int n)
{
for(int i=0;i<n;i++)
{
int x;
cout<<"Enter the value of node "<<i+1<<": ";
cin>>x;
newnode=new node(x);
if(i==0)
{
head=temp=newnode;
}
else
{
temp->next=newnode;
temp=newnode;
}
}
return(head);
}
void display(node *head)
{
while(head!=nullptr)
{
cout<<"->"<<head->data;
head=head->next;
}
}
Ive just created a constructor for creating a new node and used a temp pointer for keeping track of the last inserted element in the list. Do keep in mind it is always best to have your head pointer fixed and use another pointer for traversals. The problem with your code was that your head pointer points to the last inserted element always.
Use local variables
*head,*newnode,*temp are globals. Everytime you call a function, you're overwriting them. Make them local variables.
Memory leaks
You also leak memory in main() with:
head=getnode();
And in create() with:
temp=getnode();
Put it all together
https://repl.it/repls/MedicalEquatorialFlashmemory#main.cpp
This is my code for creating a singly-linked list in C++.
The function del_alt() deletes every alternate element starting from the second element.
The compiler gives no error as such , but during run the program terminates abruptly after showing the original list.
I have tried my best to find the possible errors but can't find any.
Help appreciated.
Cheers.
#include<iostream>
using namespace std;
class Node
{
public:
Node()
{
next=0;
}
Node *next;
int info;
};
class List
{
private:
Node *head,*tail;
public:
List()
{
head=0;
tail=0;
}
void del_alt();
void add_to_head(int);
void show_list();
};
void List :: del_alt()
{
if(!head||(head==tail))
return;
else
{
Node *current,*after,*ptr;
for(current=head,after=head->next;current!=0;current=current->next,after=current->next)
{
ptr=after;
current->next==after->next;
if(ptr==tail)
tail=current;
delete ptr;
}
}
}
void List :: add_to_head(int el)
{
Node *ptr;
ptr->info=el;
if(!head)
{
ptr->next=0;
head=tail=ptr;
}
else
{
ptr->next=head;
head=ptr;
}
}
void List::show_list()
{ Node *ptr;
cout<<"\n\n";
ptr=head;
while(ptr!=0)
{
cout<<"\t"<<ptr->info;
ptr=ptr->next;
}
}
int main()
{
List l;
int el;
char ch;
cout<<"\n\n\t\t enter elements\n\n\t";
do
{
cin>>el;
l.add_to_head(el);
cout<<"\n\t want to enter more ? (y/n) \n";
cin>>ch;
}while(ch=='y'||ch=='Y');
cout<<"\n\t Original list -> \n";
l.show_list();
l.del_alt();
cout<<"\n\t After deletion -> \n";
n.show_list();
cout<<"\n\n \\===============================================";
}
The problem comes from the non-initialization of ptr in the method add_to_head.
Node *ptr;
ptr->info=el
At least ptr should be a new allocated cell
Node *ptr = new Node;
ptr->info=el
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.
#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;
}
}
}
here in this code the compiler print error :
132 C:.... `createlist' undeclared (first use this function)
(Each undeclared identifier is reported only once for each function it appears in.)
and repeat it again in all calls in main function :(
what's the problem ?? plzzzz help me
#include<iostream>
#include<string>
using namespace std;
template <typename T>
struct Node
{
T num;
struct Node<T> *next;
// to craet list nodes
void createlist(Node<T> *p)
{ T data;
for( ; ; ) // its containue until user want to stop
{ cout<<"enter data number or '#' to stop\n";
cin>>data;
if(data == '#')
{ p->next =NULL;
break;
}
else
{ p->num= data;
p->next = new Node<T>;
p=p->next;
}
}
}
//count list to use it in sort function
int countlist (Node<T> *p)
{
int count=0;
while(p->next != NULL)
{ count++;
p=p->next;
}
return count;
}
// sort list
void sort( Node<T> *p)
{ Node<T> *p1, *p2; //element 1 & 2 to compare between them
int i, j , n;
T temp;
n= countlist(p);
for( i=1; i<n ; i++)
{ // here every loop time we put the first element in list in p1 and the second in p2
p1=p;
p2=p->next;
for(j=1; j<=(n-i) ; j++)
{
if( p1->num > p2->num)
{ temp=p2->num;
p2->num=p1->num;
p1->num=temp;
}
}
p1= p1->next;
p2= p2->next;
}
}
//add new number in any location the user choose
void insertatloc(Node<T> *p)
{ T n; //read new num
int loc; //read the choosen location
Node<T> *locadd, *newnum, *temp;
cout <<" enter location you want ..! \n";
cin>>loc;
locadd=NULL; //make it null to checked if there is location after read it from user ot not
while(p->next !=NULL)
{ if( p->next==loc)
{ locadd=p;
break;
}
p=p->next;
}
if (locadd==NULL)
{cout<<" cannot find the location\n";}
else //if location is right
{cout<<" enter new number\n"; // new number to creat also new location for it
cin>>n;
newnum= new Node/*<T>*/;
newnum->num=n;
temp= locadd->next;
locadd->next=newnum;
newnum->next=temp;
}
locadd->num=sort(locadd); // call sort function
}
// display all list nodes
void displaylist (Node<T> *p)
{
while (p->next != NULL)
{
cout<<" the list contain:\n";
cout<<p->num<<endl;
p=p->next;
}
}
};//end streuct
int main()
{
cout<<"*** Welcome in Linked List Sheet 2****\n";
// defined pointer for structer Node
// that value is the address of first node
struct Node<int>*mynodes= new struct Node<int>;
// create nodes in mynodes list
cout<<"\nCreate nodes in list";
createlist(mynodes);
// insert node in location
insertatloc(mynodes);
/* count the number of all nodes
nodescount = countlist(mynodes);
cout<<"\nThe number of nodes in list is: "<<nodescount;*/
// sort nodes in list
sort(mynodes);
// Display nodes
cout<<"\nDisplay all nodes in list:\n";
displaylist(mynodes);
system("pause");
return 0;
}
createlist is a method of your Node class, but inside main() you're calling it as a function. I recommend either treating Node like a C-struct and implementing those methods as functions taking a struct like Thomas mentions, which is how your code is structured anyway, or reading a tutorial on C++ classes.
My guess is you are missing a closing '}' for your node structure:
template <typename T>
struct Node
{
T num;
struct Node<T> *next;
}; // <--- add this line.
createlist is defined to take a parameter of Node<T> *p but you are passing it an instance of struct Node<int>*
createlist is a member method of Node. You are attempting to access Node::createlist from main. You cannot do this (even if you add "Node::" scoping to your call), because createlist is not a static method.
Change it to:
// to create list nodes
static void createlist(Node<T> *p)
and:
// create nodes in mynodes list
cout<<"\nCreate nodes in list";
Node::createlist(mynodes);
Or pull createlist out of the Node class entirely, and make it into its own function.