我有一个这样的链接列表: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停止工作......
答案 0 :(得分:0)
应该是这样的:
Node *trimList(Node* head) {
if (trimList(head->next).next == NULL && head->next->data == 0 ) {
head->next = NULL;
}
return head;
}
通过在开头而不是在结尾处调用trimList,我们确保在我们之前最多有一个0节点。
答案 1 :(得分:0)
这是我的五美分。:))
#include <iostream>
struct Node
{
int data;
Node *next;
};
void push_front( Node * &head, int data )
{
Node *tmp = new Node { data, head };
head = tmp;
}
std::ostream & display( Node * &head, std::ostream &os = std::cout )
{
for ( Node *tmp = head; tmp; tmp = tmp->next )
{
os << tmp->data << ' ';
}
return os;
}
Node * rtrim( Node * &head, int data = 0 )
{
if ( head && !rtrim( head->next, data ) && head->data == data )
{
delete head;
head = nullptr;
}
return head;
}
int main()
{
Node *head = nullptr;
for ( int x : { 0, 0, 0, 2, 1, 0, 1 } ) push_front( head, x );
display( head ) << std::endl;
rtrim( head );
display( head ) << std::endl;
rtrim( head, 2 );
display( head ) << std::endl;
rtrim( head, 1 );
display( head ) << std::endl;
rtrim( head );
display( head ) << std::endl;
rtrim( head, 1 );
display( head ) << std::endl;
}
程序输出
1 0 1 2 0 0 0
1 0 1 2
1 0 1
1 0
1
简而言之,您自己的功能可能看起来像
Node *trimtList(Node* head) {
if ( head && !trimList( head->next ) && head->data == 0 ) {
delete head;
head = nullptr;
}
return head;
}
应该像
一样调用head = trimtList( head );