【发布时间】:2015-11-01 23:18:01
【问题描述】:
我有一个这样的链接列表:1 0 1 2 0 0 0。
我想删除所有最后一个“0”节点,所以我的列表看起来像:1 0 1 2。
我尝试使用递归:
Node *trimtList(Node* head) {
if (head->next->data == 0 && head->next->next == NULL) {
head->next = NULL;
return head;
}
trimList(head->next);
return head;
}
我意识到这个方法只是删除最后一个0,而不是所有最后一个0...
Node *trimtList(Node* head) {
if (head && !trimtList(head->next) && head->data == 0) {
delete head;
head = nullptr;
}
return head;
}
int main() {
List a;
a.head= new Node(1);
a.head->next = new Node(0);
a.head->next->next = new Node(2);
a.head->next->next->next = new Node(0);
a.head->next->next->next->next = new Node(0);
a.head= trimtList(a.head);
cout << a << endl;
}
输出是1 0 2 2,然后windows已经停止工作...
【问题讨论】:
标签: c++ linked-list