Untitled

mail@pastecode.io avatar
unknown
c_cpp
7 months ago
1.7 kB
2
Indexable
Never
#include <iostream>
using namespace std;

struct Node{
    int val;
    node *next;
    
    Node(int value)
    {
        val =value;
    }
};

//  5x2+32x-1

// num  = 5
// x_next = 2

Node *convertStringList(string str)     
{
    int n = str.length();
    
    Node *head = NULL, * node = NULL;
    
    bool flag = false;
    int num = 0;
    int x_prev =0;
    int x_next = 0;
    for(int i = 0; i < n; i++)
    {
        if(str[i] == '-' || str[i] == '+')
        {
            if(str[i] == '-')
               flag = true;
        }
        
        else if(str[i] == 'x')
        {
            x_prev = x_next;
            x_next = str[i+1]-'0';
            
            int x = x_prev - x_next;       
            while(x> 1)
            {
                Node *temp = new Node(0);
                node ->next = temp;
                node = node->next;
                x--;
            }
            Node *temp = new Node(num);
            num = 0;
            if(head == NULL) {
                head = temp;
                node = temp;
            }
            
            else {
                node->next =temp;
                node=  node->next;
            }
        }
        else{
            while(str[i] >= '0' && str[i] <='9')
            {
                num = num*10+(str[i] - '0');
                i++;
            }
            
            if(flag == true)
            {
                num = num * -1;
                flag = false;
            }
        }
    }
    return head;
}
int main() {
    string a = "5x2+32x-1";
    string b = "4x3+3x2+x+3";
    
    Node *head1 = convertStringList(a);
    Node *head2 = convertStringList(b);
    
    int sum = add(head1,head2);
    cout<<sum;
	return 0;
}