In: Computer Science
C++, Write a routine that would receive a pointer to the top of the linked list that has an integer for each node. Count all positive even integers in the linked list but make negatives into positives. Return the count negatives that became positives. Hint, use Node<ItemType>* to define pointers and use pointers to go through the linked list.
Here is the well commented function.
#include<bits/stdc++.h>
using namespace std;
/*This is the node structure which have one data field and one pointer to next field.
class Node
{
public:
int data;//data field
Node *next;//pointer to next node.
Node(int x){data=x;next=NULL;}//constructor to initialize the Node.
};
*/
//Method to Count all positive even integers in the linked list.
//but make negatives into positives.
// Return the count negatives that became positives.
int func(Node *top)
{
int evenpositive=0;//count of even positive integers in linked list.
Node *temp=top;//temporary variable to traverse through linked list.
int negTOpos=0;//count of negatives even integers that became positives.
//while loop to traverse through linked list.
while(temp)
{
//if node's data is positive even integer
if(temp->data>0 && temp->data%2==0)
evenpositive++;
//if node's data is negative even integer
else if(temp->data<0&& temp->data%2==0)
{
temp->data= 0-(temp->data);//Make it positive.
negTOpos++;//Increment negTOpos.
}
temp=temp->next;//go to next node.
}
return negTOpos;//return count of negatives even integers that became positives.
}
Here is the output for linked list.
(1)---->(-2)---->(-4)---->(6)---->(11)---->(-7).
If you like the above information than please do an upvote.