{
int data;
Node* next;
Node(const int dataval, Node* nextval = NULL)
{
data = dataval;
next = nextval;
}
Node(Node* nextval = NULL)
{
next = nextval;
}
}LNode;
class LList
{
public:
LList(int size);
~LList();
void clear();
void append(int &value);
int remove();
int length();
void moveToStart();
void moveToPos(int &pos);
void display();
int find(int value);
private:
LNode* head;
LNode* tail;
LNode* curr;
int cnt;
};
LList::LList(int size)
{
curr = tail = head = new Node();
cnt = 0;
}
LList::~LList()
{
while (head != NULL)
{
curr = head;
head = head->next;
delete curr;
}
}
void LList::clear()
{
LList::~LList();
curr = tail = head = new Node();
cnt = 0;
}
void LList::append(int &value)
{
tail = tail->next = new Node(value, NULL);
cnt++;
}
void LList::display()
{
int cnt2 = cnt;
curr = head->next;
while (cnt2)
{
std::cout << curr->data << " ";
curr = curr->next;
cnt2--;
}
std::cout << std::endl;
}
int LList::length()
{
return cnt;
}
int LList::find(int value)
{
int pos = 0;
if (head == tail)
{
std::cout << "链表是空链表!" << std::endl;
return -1;
}
while (value != curr->next->data && curr != tail)
{
if (curr->next != tail)
{
curr = curr->next;
if (curr == tail)
break;
pos++;
}
else
{
if (curr->data == value)
{
pos = length() - 1;
}
else
{
pos = -1;
break;
}
}
}
return pos;
}
int LList::remove()
{
int it = curr->next->data;
LNode* ltemp = curr->next;
curr->next = curr->next->next;
delete ltemp;
cnt--;
return it;
}
void LList::moveToStart()
{
curr = head;
}
void LList::moveToPos(int &pos)
{
if (pos == -1)
{
return;
}
curr = head;
for (int i = 0; i< pos; i++)
curr = curr->next;
}
int main()
{
int inputValue;
int pos;
int delValue = 0;
LList ll(100);
ll.clear();
std::cout << "从键盘中输入5个整数:" << std::endl;
for (int i = 0; i < 5; i++)
{
std::cin >> inputValue;
ll.append(inputValue);
}
std::cout << "从键盘上输入后的链表:" << std::endl;
ll.display();
ll.moveToStart();
pos = ll.find(15);
if (pos == -1)
{
std::cout << "链表中不存在指定的值" << std::endl;
return 0;
}
ll.moveToPos(pos);
delValue = ll.remove();
std::cout << "删除链表的第"<< pos <<"个位置,值为"<< delValue <<" 后的链表为:" << std::endl;
ll.display();
return 0;
}
本人测试可行,但是还有些问题没有弄清楚,亟待反馈。网上查询过,struct中可以包含构造函数,但是必须带有参数的形式。