Implementing Polynomials using Singly Linked List in C++
Greetings!!!!
Please find the implementation of polynomial using singly linked list in c++ with a sample run screen shot.
#include <iostream>
#include <malloc.h>
#include<conio.h>
using namespace std;
//Node of the polynomial linked list is implemented by below structure
struct node
{
int exponent;
int cofficient;
struct node *next;
};
//Initially set start pointer to point to the NULL
struct node *start=NULL;
// Function declaration to create polynomial.
struct node *create_Polynomial(struct node *);
// Function declaration to display polynomial.
struct node *display_Polynomial(struct node *);
int main()
{
// choice is read by user for creation of polynomial, display of polynomial, and exit from program.
int choice;
do
{
//Display the menu for polynomial.
cout<<"\n\n\nmain menu";
cout<<"\n1.Enter the polynomial";
cout<<"\n2.Display the polynomial";
cout<<"\n3.Exit";
//Take input as choice for creation of polynomial, display of polynomial, and exit from program
cout<<"\nEnter Your Choice: ";
cin>>choice;
switch(choice)
{
case 1:
start=create_Polynomial(start);
cout<<"\n Polynomial Created Successfully!!! \n";
break;
case 2:
cout<<"\nPolynomial is displayed as below:\n";
start=display_Polynomial(start);
}
}while(choice!=3);
getch();
return 0;
}
// Function to create polynomial.
struct node *create_Polynomial(struct node *start)
{
cout<<"\n Enter exponent value in descending order";
struct node *newNode,*ptr;
int exponent,cofficient;
cout<<"\nEnter the exponent: ";
cin>>exponent;
cout<<"\nEnter its cofficient: ";
cin>>cofficient;
while (exponent!=-1)
{
//Create new Node of polynomial
newNode=new struct node();
//Assigning cofficient and exponent to the term.
newNode->exponent= exponent;
newNode->cofficient= cofficient;
// Setting last node to point to the NULL.
newNode->next=NULL;
//Check if it is first node of polynomial
if (start==NULL)
{
start=newNode;
}
else
{
ptr=start;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
//Adding new node to the last of linked list.
ptr->next=newNode;
}
//Take input as exponent
cout<<"\n Enter exponent or -1 to stop crating polynomial: ";
cin>>exponent;
//Check for -1, if wanted to end with cration of polynomial
if (exponent==-1)
break;
//Take input as cofficient.
cout<<"\n Enter its cofficient: ";
cin>>cofficient;
}
return start;
}
// Function to display polynomial
struct node *display_Polynomial(struct node *start)
{
//Loop every term (Node) of polynomial.
while(start!=NULL)
{
if(start->exponent!=0)
{
if(start->cofficient<0)
cout<<start->cofficient<<"x^"<<start->exponent;
else
cout<<"+"<<start->cofficient<<"x^"<<start->exponent;
}
else
{
if(start->cofficient<0)
cout<<start->cofficient;
else
cout<<"+"<<start->cofficient;
}
start=start->next;
}
return start;
}
Thank You
Get Answers For Free
Most questions answered within 1 hours.