我想创建它接受由参考值insertAfter功能,然后插入当前节点之后的价值。我不能确定如何实现的代码。
下面是头文件,什么我都试过,但它不编译。
#include <iostream>
#include <string>
class DoublyLinkedList {
public:
DoublyLinkedList();
~DoublyLinkedList();
void append (const string& s);
void insertBefore (const string& s);
void insertAfter (const string& s);
void remove (const string& s);
bool empty();
void begin();
void end();
bool next();
bool prev();
bool find(const string& s);
const std::string& getData() const;
private:
class Node
{
public:
Node();
Node(const string& data);
~Node();
Node* next;
Node* prev;
string* data;
};
Node* head;
Node* tail;
Node* current;
};
void DoublyLinkedList::insertAfter(const string& s)
{
// Node *temp, *var;
//var=(Node *)malloc(sizeof(Node));
if(head == NULL)
{
append(s);
}
temp->data=current;
}
void DoublyLinkedList::append(const string& s)
{
//create a new Node
current = new Node(s);
if (this->empty())//check if it is empty or not
{
this->head = this->tail = current;
}else{
//append to tail
current->prev = tail;
tail->next = current;
tail = current;
}
}
#endif
- 创建一个新的节点和存储传入的数据,设置当前指针到头部。
Node * newNode = new Node(s);
current=head;
- 必须使用一个循环,其检查使用两个指针,其中一个落后该检查节点的值的一个在后面的每个节点的值横穿过链表。
while(current->data != insertAfter-
>data)
{
current=current->next;}
- 一旦正确的节点发现电流回路应停止。设置新节点的下一个指针insertAfter的下一个指针,而上一个指针insertAfter节点。
newNode->next = insertAfterNode->next;
newNode->prev = insertAfterNode;
那么 - 你目前的下一个指针设置为你想插入的节点。
current->next = newNode;
此外,一定要添加的每个潜在的情况。如果它是被插入后的尾巴,如果插在头上一定要设置尾指针newNode和相同的。用循环遍历后,放:
if(tail->data==current->data)
{
tail = newNode;
}
if(head->data==current->data)
{
head=newNode;
}
编辑:因为这是一个双向链表,在上一个指针来代替trailCurrent,这是没有必要的来实现。