c++ - Delete all the last node of linked list which have value = 0 -
i have linked list this: 1 0 1 2 0 0 0
. want delete last "0" node list can like: 1 0 1 2
. tried using recursion:
node *trimtlist(node* head) { if (head->next->data == 0 && head->next->next == null) { head->next = null; return head; } trimlist(head->next); return head; }
i realize method delete last 0, not last 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 << << endl; }
the output 1 0 2 2
, windows has stop working...
it should like:
node *trimlist(node* head) { if (trimlist(head->next).next == null && head->next->data == 0 ) { head->next = null; } return head; }
by calling trimlist @ beginning rather @ end make sure there @ 1 0 node ahead of ours.
Comments
Post a Comment