0
我需要重載Node類中的++運算符,以便在我調用它時返回下一個節點的指針。以及 - 返回前一個。我根本不熟悉重載操作符,所以我對如何解決這個問題非常失望。我認爲我的語法有點正確,但我不確定如何實現它。我是否使用它的會員功能?任何幫助將不勝感激!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
如果我的答案解決了您的問題,請不要忘記接受它(單擊答案投票計數下方的「V」標記)。在SO上這樣做通常是一個好習慣。 – Spook 2013-03-04 06:36:31
將在4分鐘內完成:) – user2130537 2013-03-04 06:37:29
只是一個簡單的問題。我如何在我的LL課中打電話給我?我所嘗試的一切似乎都會使我的程序崩潰 – user2130537 2013-03-04 06:46:19