如何实现push_front()
单链表的方法作为其成员函数?下面的代码无法编译 ( error: lvalue required as left operand of assignment
),因为您不能分配给this
指针。有什么办法解决这个问题?
#include<algorithm>
using namespace std;
class ListElem{
public:
ListElem(int val): _val(val){}
ListElem *next() const { return _next; }
void next(ListElem *elem) { _next = elem; }
void val(int val){ _val = val; }
int val() const { return _val;}
void print();
void push_front(int);
private:
ListElem *_next;
int _val;
};
void ListElem::push_front(int val)
{
ListElem *new_elem = new ListElem(val); //new node
new_elem->next( this ); // new node points to old head
this = new_elem; // make new node the new head, error!
return;
}
void ListElem::print()
{
ListElem *pelem = this;
while(ListElem *pnext_elem = pelem->next())
{
cout << pelem->val() << ' ';
pelem = pnext_elem;
}
cout << pelem->val() << endl;
}
int main()
{
//initialization
ListElem *head = new ListElem(1);
ListElem *elem = head;
for (int ix = 2; ix < 10; ++ix)
{
ListElem *elem_new = new ListElem(ix);
elem -> next(elem_new);
elem = elem_new;
}
head->print();
//insert at the beginning
head->push_front(7);
head->print();
}