On Jul 16, 9:37*am, aki <akhileshrawat...@gmail.comwrote:
#include<iostream>
using namespace std;
Don't do that. Use the std:: decorator on things from std.
const int *NU=10;
struct node {
* * * * * * * * int data;
* * * * * * * * node *ptr;
* * * * * * };
int main()
{
* * * * int NU;
* * * * cout<<"enter nu"<<endl;
* * * * cin>>NU;
Note that this NU hides the NU you declared earlier.
* * * * node* ARR[NU]; // Array of pointers to type node * * * *Is this Ok
Note that this should not compile on standard
compliant compiler as NU is not a compile time
constant. If you need values that are chosen
at run time, you need ot be looking at new[]
and delete[].
Your compiler may be allowing the extension.
If so, you should be looking for flags on your
compiler that make it picky about not allowing
extensions. Always make yor compiler as picky
as you can.
* * * * for(int i=1;i<=NU;i++)
* * * * {
* * * * * *ARR[i]=new node;
* * * * * *ARR[i]->data=i;
* * * * }
This loop needs to go from 0 to NU-1. Read the
note following.
* * * * for(int i=1;i<=NU-1;i++)
* * * * {
* * * * * *ARR[i]->ptr =ARR[i+1];
* * * * }
Needs to go from 0 to NU-2.
It looks like you are setting up a linked list.
But the elements of that linked list are also
in an array. This looks very strange.
If you want a linked list, you need to be doing
a linked list. (Though you are much better off
learning the standard containers first.) If you
want an array, you need to be doing an array.
Overlapping them like this is whacky.
* * * * node *head=ARR[1];
Needs to be ARR[0]
* * * * ARR[NU]->ptr=NULL;
Needs to be ARR[NU-1]
You need to more carefully read your introductory
text on C++. Arrays go from 0 to dimension minus 1.
So, even if your compiler allowed the extension
previously mentioned, this is wrong. If you enter
7 for NU, the elements of the array would be ARR[0]
through AR[6]. Referencing ARR[7] is a problem.
It looks like (though I can't be sure) you accidentally
"got away with it" here.
But changes to your code might produce weird behaviour.
When you do this line
ARR[i]=new node;
with i == 7, it will be writing to memory outside the
array. You don't want to be doing that.
* * * * node *tmp =head;
* * * * while(tmp->ptr!=NULL)
This is saying, as long as the current node has a next
node, keep going. But when you get to the 7th node,
it does not have a next node.
Should be this.
while(tmp != NULL)
Which means, as long as there is a current node, keep going.
Note that this works even if the linked list is empty.
* * * * {
* * * * * * * * static int c=1;
* * * * * * * * cout<<"node"<<c<<"="<<tmp->data<<endl;
* * * * * * * * c++;
What is the variable c for? It does not seem to get used.
* * * * * * * * tmp=tmp->ptr;
* * * * }
* return 0;
}
output
enter nu
7
node1=1
node2=2
node3=3
node4=4
node5=5
node6=6
Why is 7th node not getting printed???
Hope you get it now.
Socks