创建一个链表删除指定的数值。

typedef struct Node
{
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中可以包含构造函数,但是必须带有参数的形式。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值