简体   繁体   中英

Reverse linked list using overloading operator-

I need to reverse all nodes in my list.

My code:

#include<iostream>
#include<stdlib.h>
using namespace std;
struct elem
{
    int inf;
    elem *adr;
    elem(int n, struct elem *p): inf(n),adr(p) {}
};
class list
{
    elem *prim,*p;
public:
    void afisare_lista ();
    list(void)
    {
        prim=NULL;
    };
    list(int);
    list operator-() const;
    list operator-(elem *current);
};

list::list(int nr)
{
    int inf;
    cin>>inf;
    prim=new elem(inf,NULL);
    elem*q=prim;
    for(int i=1; i<nr; i++)
    {
        cin>>inf;
        p=new elem(inf,NULL);
        q->adr=p;
        q=p;
    }
    p=prim;
}
void list::afisare_lista()
{
    elem *t;
    cout<<"\n";
    t=prim;
    while(t!=NULL)
    {
        cout<<t->inf<<" ";
        t=t->adr;
    }
}
list list::operator-() const
{
    elem *v;
    v = prim;
    while (v!=NULL)
    {
        cout<<-v->inf<<" ";
        v = v->adr;
    }

}

list list::operator-(elem *current)
{
    current = prim;
    elem* prev = NULL, *next = NULL;

    while (current != NULL)
    {
        next = current->adr;
        current->adr = prev;
        prev = current;
        current = next;
    }
    prim = prev;

}

int main()
{
    list l(6);
    l.afisare_lista();
    -l;
    cout<<"\n";
}

For example:

Input: 1 2 3 4 5 6

Output: 6 5 4 3 2 1

not sure what it is "minimal reproducible example", but is full code. Second function( list list::operator-(elem *current) ) I want to use for revers list. First for multiply every node with -1 ( list list::operator-() const )

How can i call the second method for reverse my list.

Your overlaod operator is list list::operator-(elem *current) . it is an arithmetic form of list a - elem * b as follows:

int main()
{
   list l(6);
   std::cout << "Origin sequence : "; l.afisare_lista(); std::cout<<std::endl;
   elem* a = new elem(0, NULL);
   l - a;
   std::cout << "Reverse sequence: "; l.afisare_lista(); std::cout<<std::endl;
}

It renders the result:

1 2 3 4 5 6
Origin sequence :
1 2 3 4 5 6
Reverse sequence:
6 5 4 3 2 1

Although the return of overlaod operators are irrelavant to your purpose, it looks good to get rid of the compiler warning by returning itself following the convention:

 // class list { elem *prim,*p; public: void afisare_lista (); list(void); list(int); list& operator-(); list& operator-(elem *current); //add "return *this;" at the end of these functions // It make no difference but stop the warning messages. };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM