我需要在Node类中重载++操作符,以便当我调用它时,它返回下一个节点的指针。还有一个返回前一个的。我对重载操作符一点也不熟悉,所以我很不知道如何操作它。我想我已经得到了语法有些正确,但我不确定如何实现它。我要用它创建一个成员函数吗?任何帮助将非常感激!
My Node类:
#ifndef NODE_H
#define NODE_H
class Node
{
public:
Node(Node* n = NULL, int v =0)
{
next = n;
value = v;
}
LinkedList& operator++(const LinkedList )
Node* next;
Node* prev;
int value;
};
#endif
不确定是否有帮助,但这是我的LinkedList
文件:
#ifndef LinkedList_H
#define LinkedList_H
#include "Node.h"
#include <iostream>
using namespace std;
class LinkedList{
public:
LinkedList()
{
front = NULL;
back = NULL;
size = 0;
}
void push_front(int item)
{
if (front == NULL)
{
front = new Node(NULL, item);
back = front;
size++;
return;
}
Node* newNode = new Node(NULL, item);
front->prev = newNode;
newNode->next = front;
front = newNode;
size++;
}
int pop_front()
{
if (front == NULL){
cout<<"No item to pop "<<endl;
return 0;
}
Node *temp = front;
int value = front->value;
if(front->next){
front = front->next;
front->prev = NULL;
size--;
delete temp;
return value;
}
front = NULL;
back = NULL;
return value;
}
int pop_back()
{
if(front == NULL){
cout<<"Nothing to pop! ";
return 0;
}
else{
Node *prev = front;
Node *succ = front->next;
while(succ->next != NULL){
succ = succ->next;
prev = prev->next;
}
int value = succ->value;
prev->next = NULL;
back = prev;
delete succ;
size--;
return value;
}
}
void push_back(int item)
{
if (front == NULL)
{
front = new Node(NULL, item);
size++;
return;
}
else {
Node* newnode = new Node(NULL, item);
Node *succ = front;
while(succ->next != NULL){
succ = succ->next;
}
succ->next = newnode;
newnode->next = NULL;
newnode->prev = succ;
back = newnode;
size++;
}
}
void print()
{
if (front == NULL){
cout<<"Nothing to print! "<<endl;
}
Node *p = front;
while(p){
cout<<p->value<<" ";
p=p->next;
}
cout<<endl<<endl;
}
bool removeNode(int i){
if (i < 0 || i >= size) //assume size is a data member of double linked
return false;
if (front == NULL)
return false;
if (i == 0)
{
Node* p = front; //assume front is a data member of double linked list
front = front->next;
front-> prev = NULL;
delete p;
size--;
if (size == 1)
back = front;
return true;
}
int temp=0;
Node* curr = front;
Node* p = NULL;
while (temp!= (i-1) && curr->next !=NULL)
{
p = curr;
curr = curr->next;
temp++;
}
p->next = curr->next;
curr->next->prev = p;
delete curr;
size--;
if (size == 1)
back = front;
return true;
}
LinkedList& operator++(const LinkedList )
Node* front; //front of a linked list
Node* back;
int size; //# of nodes in a linked list
};
#endif
我认为,它应该是这样的:
#ifndef NODE_H
#define NODE_H
class Node
{
public:
Node(Node* n = NULL, int v =0)
{
// Where do you set prev?
next = n;
value = v;
}
Node * operator ++ (int)
{
return next;
}
Node * operator -- (int)
{
return prev;
}
Node* next;
Node* prev;
int value;
};
#endif
请参阅c++常见问题解答中有关操作符重载的更多信息。