在链表中的某个地方插入一个节点C++
问题描述:
我有一个链表,我需要在“迭代器”位置插入一个节点。在链表中的某个地方插入一个节点C++
下面是插入功能(这是我模板):
template <class T>
void List<T>::insert(T x)
{
if (size=0)
{
cout << "adding postion to head because empty list" << endl;
NodeRef newNode = new Node(x);
tail = head = newNode;
}
else
{
NodeRef temp = new Node(x);
temp->previous = iterator;
iterator->next = iterator;
}
}
下面是链表类(我也模板):
class List
{
private:
struct Node
{
T data;
Node* next;
Node* previous;
Node() : next(NULL), previous(NULL) {} //define our own default constuctor
Node(T data) : next(NULL), previous(NULL), data(data) {}
};
typedef struct Node* NodeRef;
NodeRef head;
NodeRef tail;
NodeRef iterator; //points to one node at a time
NodeRef current1;//temp
int size;
public:
void insert(T);Inserts a new element into the list in the position after the "iterator"
void scroll() {iterator = iterator->next;}
当我打电话插入功能,我遇到了问题。滚动功能正常工作。
答
iterator->next = iterator
不正确,并创建一个循环。由于上一行是temp->previous = iterator
,iterator->next
应该指向温度。一旦你更新了这两个链接,你应该有n->next->prev == n
列表中的任何有效节点。