Advertisement
dude2099

Introducere valoare intre noduri

Oct 15th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct nod
  6. {
  7.     int info;
  8.     nod* adr;
  9. };
  10.  
  11. int n;
  12.  
  13. int inserare(nod*&prim, int k, int inf)
  14. {
  15.     nod* p,*q;
  16.     if(k>n+1) return 0;
  17.     else
  18.     {
  19.         nod* p=new nod;
  20.         p->info=inf;
  21.         if(k==1) {
  22.             p->adr=prim;
  23.             prim=p;
  24.         } else if(k==n+1) {
  25.             q=prim;
  26.             while(q->adr!=NULL)
  27.                 q=q->adr;
  28.             q->adr=p;
  29.             p->adr=NULL;
  30.         } else {
  31.             q=prim;
  32.             int ct=1;
  33.             while(ct<k-1)
  34.             {
  35.                 q=q->adr;
  36.                 ct++;
  37.             }
  38.             p->adr=q->adr;
  39.             q->adr=p;
  40.         }
  41.         return 1;
  42.     }
  43. }
  44.  
  45. void parcurgere(nod* v)
  46. {
  47.     nod* c=v;
  48.     while(c)
  49.     {
  50.         cout<<c->info<<" ";
  51.         n++;
  52.         c=c->adr;
  53.     }
  54. }
  55.  
  56. nod* creare2()
  57. {
  58.     nod* prim, *ultim, *p;
  59.     int nr;
  60.     prim=new nod;
  61.     ultim=prim;
  62.     cout<<"Introduceti un numar: "; cin>>nr;
  63.     if (nr==0)
  64.     {
  65.         cout<<"Lista este vida.";
  66.         return 0;
  67.     }
  68.     else
  69.     {
  70.         prim->info=nr;
  71.         prim->adr=NULL;
  72.         cout<<"Introduceti un numar: "; cin>>nr;
  73.         while(nr){
  74.             p=new nod;
  75.             p->info=nr;
  76.             ultim->adr=p;
  77.             ultim=p;
  78.             ultim->adr=NULL;
  79.             cout<<"Introduceti un numar: "; cin>>nr;
  80.         };
  81.         return prim;
  82.     }
  83. }
  84.  
  85. int main()
  86. {
  87.     nod* prim;
  88.     int k, inf;
  89.     prim=creare2();
  90.     parcurgere(prim);
  91.     cout<<"Numarul de noduri este: "<<n<<endl;
  92.     cout<<"Pentru inserare, introduceti pozitia si valoarea: "; cin>>k>>inf;
  93.     if(!inserare(prim,k,inf)) cout<<"\nPozitia introducsa nu se afla in lista.";
  94.     else parcurgere(prim);
  95.     return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement