C++循环链表问题,调试的时候一直显示*****是nullptr,求问怎么解决
代码如下
#ifndef _LinkedList_H_#define _LinkedList_H_
using namespace std;
template <class T>
class LinkedList
{
private:
struct node
{
T data;
node*next;
node(const T& x, node* n = NULL) :data(x), next(n) {};
node() :next(NULL) { data = 0; };
};
node* head;
int size;
protected:
node* get(int i)const
{
if (i < 0)return head;
node* p = head->next;
for (int j = 0; j < i; j++)
p = p->next;
return p;
}
public:
LinkedList() :size(0)
{
head = new node;
}
~LinkedList()
{
clear();
delete head;
}
int length()
{
return size;
}
void clear()
{
while (length() > 0) remove(0);
}
void insert(int i, const T&x)
{
node* p = get(i - 1);
p->next = new node(i, p->next);
size++;
}
void remove(int i)
{
node* p = get(i - 1);
node* q = p->next;
p->next = q->next;
delete q;
--size;
}
int search(const T& x)const
{
node* p = head->next;
for (int i = 0; p; ++i)
{
if (x == p->data)
return i;
p = p->next;
}
return -1;
}
T visit(int i)const
{
return get(i)->data;
}
void traverse()const
{
node* p = head->next;
while (p)
{
cout << p->data << endl;
p = p->next;
}
}
void erase(int x, int y)
{
int i;
node* p = get(x - 1);
node* q = p->next;
for (i = x; i <= y; i++)
{
p->next = q->next;
delete q;
q = p->next;
}
}
};
#endif
#include <iostream>#include "LinkedList.h"
using namespace std;
int main()
{
LinkedList <int> list;
int n;
cout << "input n" << endl;
cin >> n;
int *arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = i;
}
for (int i = 0; i < n; i++)
{
list.insert(i,arr[i]);
}
cout<<list.search(2);
list.erase(1,3);
list.traverse();
delete[]arr;
return 0;
}
回答
你的
void erase(int x, int y)
实现有问题,没有删除元素后把列表长度减一;应改为
void erase(int x, int y) {
int i;
node* p = get(x - 1);
node* q = p->next;
for (i = x; i <= y; i++)
{
p->next = q->next;
delete q;
q = p->next;
--size;
}
}
以上是 C++循环链表问题,调试的时候一直显示*****是nullptr,求问怎么解决 的全部内容, 来源链接: utcz.com/a/41063.html