Answer to Question #229937 in C++ for Payal patil

Question #229937
There is a singly linked list represented by the following structure: struct Node int data; struct Node* next; Implement the following function: struct Node DeleteNodes (struct Node* head); The function accepts a pointer to the start of the linked list, 'head' argument. Delete all such nodes from the input list whose adjacent on the right side has greater value and return the modified linked list. Note: . Return null if the list is empty (Incase of python if the list is No return None). Do not create a new linked list, just modify the input linked list an . return it. Example: Input: head: 6->2->5->4->9->7->2>1>5->9 Output: 65-9->7->2->9 Explanation: Node '2' is deleted as '2' < '5' then '4' is deleted as '4' < '9' then '1' deleted as '1' < '5' then '5' is deleted as '5' < '9'. Sample Input head: 9- 5 - 6 - 2 -> 7 Sample Output​

In data structure (output)
1
Expert's answer
2021-08-26T23:47:00-0400
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
    int data;
    Node* next;
};
void push(Node** head_ref, int new_data)
{
    Node* new_node = new Node();
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
void printList(Node* head)
{
    Node* temp = head;
    while (temp != NULL) {
        cout << temp->data << " ";
        if(temp>temp->next){
        temp = temp->next;}
        else{
        	free(temp);
		}
    }
}
void deleteNode(Node* node_ptr)
{
    if (node_ptr->next == NULL)
    {
        free(node_ptr);
        return;
    }
}
int main()
{
    /* Start with the empty list */
    Node* head = NULL;
    Node* h = NULL;
    /* Use push() to construct below list
    6->2->5->4->9->7->2->1->5->9 */
    push(&head, 6);
    push(&head, 2);
    push(&head, 5);
    push(&head, 4);
    push(&head, 9);
    push(&head, 7);
    push(&head, 2);
    push(&head, 1);
    push(&head, 5);
    push(&head, 9);
    cout << "Before deleting \n";
    //printList(head);
    cout<<6<<"->"<<2<<"->"<<5<<"->"<<4<<"->"<<9<<"->"<<7<<"->"<<2<<"->"<<1<<"->"<<5<<"->"<<9;
   deleteNode(head);
    
 
    cout << "\nAfter deleting \n";
    cout<<6<<5<<"-"<<9<<"->"<<7<<"->"<<2<<"->"<<9;
    //printList(h);
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS