Linked list representation of a polynomial - c

I have to write a program to sum two polynomials. For the purpose, first of all, I am writing a program to take two polynomials and print them.
My program is like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int power;
int coef;
struct node *link;
};
int input( struct node *Phead);
int display( struct node *Phead);
int main()
{
struct node *Phead= malloc(sizeof(struct node)),*Qhead = malloc(sizeof(struct node));
input(Phead);
display(Phead);
input(Qhead);
display(Qhead);
return 0;
}
int input( struct node *Phead)
{
//Phead
//Qhead = malloc(sizeof(struct node));
int value;
printf("\n\t\tEntry of polynomial:\n");
printf("Enter the coefficient: ");
scanf("%d",&Phead->coef);
printf("Enter the power: ");
scanf("%d",&Phead->power);
Phead->link = NULL ;
printf("Enter the coefficient,( 0 to break ): ");
scanf("%d", &value);
while ( value != 0 )
{
struct node *new_node = malloc(sizeof(struct node ));
new_node -> coef = value;
printf("Enter the power: ");
scanf("%d",&new_node->power);
new_node->link = Phead;
Phead = new_node;
//printf("%d",Phead->power);
printf("Enter the coefficient,( 0 to break ): ");
scanf("%d", &value);
}
return 0;
}
int display( struct node *Phead)
{
struct node *temp = Phead;
//printf("I am in display.\n");
while ( temp != NULL )
{
//printf("I am in while.\n");
printf("%d * x ^ %d + ",temp->coef,temp->power);
temp=temp->link;
}
//printf("%d * x ^ %d + ",temp->coef,temp->power);
//printf("0");
return 0;
}
I am unable to print the polynomial.The issue is with temp variable. Please help me to solve this.

The problem is with your this part of code:
new_node->link = Phead;
Phead = new_node;
Solve it as follows:
Phead->link = new_node;
Phead = new_node;

Related

Linked list unable to print all elements

I'm trying to print the linked list to which I prompt for user input.
This code below is not printing the whole list, only the last element at a time.
I don't seem to find the bug. Can you please take a look at it?
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
struct Node *head;
void Insert(int x) {
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = x;
temp->next = NULL;
head = temp;
};
void Print() {
struct Node *temp = head;
printf("Linked list is: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
};
int main() {
head = NULL;
int i, x;
for (i = 1; i <= 10; i++) {
if (i == 1) {
printf("Enter 1st number: \n");
} else if (i == 2) {
printf("Enter 2nd number: \n");
} else {
printf("Enter %dth number: \n", i);
}
scanf("%d", &x);
Insert(x);
Print();
}
}
temp->next = NULL; is the culprit. It should be temp->next = head;.
Another (more cornercase) issue is that your code fails to check for errors in malloc and scanf.
Edit in response to comment:
If you want to append (as opposed to prepend), you'll need to keep a tail pointer for forward traversal and then either use a dummy first node (avoids a branch) or special-case an insert to an empty list.
Example of both (with simplistic error handling via exit(1)) in one piece of code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
#define DUMMYFIRST 1 //change to 0 to compile the other variant
#if DUMMYFIRST
struct Node dummyfirst;
struct Node *head=&dummyfirst;
#else
struct Node *tail,*head=0;
#endif
void Insert(int x) {
struct Node *newnode = malloc(sizeof(struct Node));
//don't cast the result of malloc in C
//https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc
if(!newnode) { perror("malloc"); exit(1); }
newnode->data = x;
newnode->next = 0;
#if !DUMMYFIRST
if(!tail) tail = head = newnode;
else head->next = newnode;
#else
head->next = newnode;
#endif
head = newnode;
};
void Print() {
#if DUMMYFIRST
struct Node *newnode = dummyfirst.next;
#else
struct Node *newnode = tail;
#endif
printf("Linked list is: ");
while (newnode != NULL) {
printf("%d ", newnode->data);
newnode = newnode->next;
}
printf("\n");
};
int main() {
int i, x;
for (i = 1; i <= 10; i++) {
if (i == 1) {
printf("Enter 1st number: \n");
} else if (i == 2) {
printf("Enter 2nd number: \n");
} else {
printf("Enter %dth number: \n", i);
}
if(1!=scanf("%d", &x)) exit(1);
Insert(x);
Print();
}
}
A more library friendly approach to handling errors would be to propagate the error to the caller, i.e., instead of exiting with an error message right away, you'd change the return value from void to something indicating the error, e.g. so that the caller could check and decide what to do (print it, print it in a localized version, try a different algorithm...)
E.g.:
struct Node *Insert(int x) {
struct Node *newnode = malloc(sizeof(struct Node));
//don't cast the result of malloc in c
//https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc
if(!newnode) return NULL;
//...
};
//...
//calling code:
if(!Insert(x)) perror("Insert"),exit(1);
When you insert the new node, you do not link the rest of the list, instead of temp->next = NULL; you should write
temp->next = head;
To ensure defined behavior, you should check for memory allocation failure and invalid input.
Also remove the dummy ; after the function bodies.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
struct Node *head;
int Insert(int x) {
struct Node *temp = malloc(sizeof(*temp));
if (temp) {
temp->data = x;
temp->next = head;
head = temp;
return 1;
} else {
return 0;
}
}
void Print(void) {
struct Node *temp = head;
printf("Linked list is: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
static char suffix[4][3] = { "th", "st", "nd", "rd" };
int i, x;
for (i = 1; i <= 10; i++) {
int suff = (i >= 1 && i <= 3) ? i : 0;
printf("Enter %d%s number:\n", i, suffix[suff]);
if (scanf("%d", &x) != 1) {
fprintf(stderr, "invalid or missing input\n");
break;
}
if (!Insert(x)) {
fprintf(stderr, "cannot allocate memory for Node\n");
return 1;
}
Print();
}
return 0;
}

Graphs: for an adjacency matrix

I have to write a program, whitch will show out graph results in the form of an adjacency list and adjacency matrix. I've guided myself by a tutorial on YT on how to implement the adjency list, and with the current stored data (whitch the user is introducing himself, like the number of nodes, edges, to how many edges a edge is connected and to which one) and I want to know/understand how, with the already stored data, to build a adjacency matrix.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void read_graf(struct node *ad[], int no_of_nodes);
void print_graf(struct node *ad[], int no_of_nodes);
int main()
{
int op;
int i,j,k, nodes;
begin:
printf("Type in the number of edges: ");
scanf("%d", &nodes);
struct node *adj[nodes];
for (i=0;i<nodes;i++)
adj[i] = NULL;
read_graf(adj,nodes);
print_graf(adj,nodes);
printf("\nDo you want to try again? 1 for yes and 0 for no: ");
scanf("%d", &op);
if (op==1)
goto begin;
else
{
printf("Thank you for visiting! :)");
exit(0);
}
return 0;
}
void read_graf(struct node *ad[], int no_of_nodes)
{
struct node *new_node;
int i,j,k, val;
for (i=0;i<no_of_nodes;i++)
{
struct node *last= NULL;
printf("\n To how many edges is edge %d connected to: ", i+1);
scanf("%d", &k);
for (j=0;j<k;j++)
{
printf("To which edges is it connected : ");
scanf("%d", &val);
new_node = (struct node *)malloc(sizeof(struct node*));
new_node->data = val;
new_node->next = NULL;
if(ad[i]==NULL)
ad[i]= new_node;
else
last->next = new_node;
last = new_node;
}
}
}
void print_graf(struct node *ad[], int no_of_nodes)
{
struct node *ptr = NULL;
int i,j;
for(i=0;i<no_of_nodes;i++)
{
ptr = ad[i];
printf("\n x%d : ", i+1);
while(ptr != NULL)
{
printf("%d,\t", ptr->data);
ptr = ptr->next;
}
printf("0");
}
}
If you only need to print out the adjacency matrix and assuming that a 1 would represent a connection between node i and node j, you just have to slightly modify the inner loop inside the print_graf function.
void print_as_mat(struct node *ad[], int no_of_nodes)
{
struct node *ptr = NULL;
for(int i = 0; i < no_of_nodes; ++i)
{
ptr = ad[i];
// Loop over all the possible nodes
for(int j = 0; j < no_of_nodes; ++j)
{
if ( ptr && ptr->data == j ) {
// ^^^^^^^^^^^^^^ Check if the index correspond to the
// current node in the adjacency list.
printf(" 1");
// update the current node in the list, but only here.
ptr = ptr->next;
}
else {
printf(" 0");
}
}
// The row is completed.
putchar('\n');
}
}

How can I print input data?

As a practice for final exam, I am practicing a linked list. But now I am stuck at printing input data on my code. I made this linked list and want to print input data. But my code does not print anything.
What's wrong with my code?
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int a,b ;
struct Node* next;
}NODE;
void makenode()
{
int a;
int b;
printf("enter the name : ");
scanf("%d",&a);
printf("enter the sur name : ");
scanf("%d",&b);
NODE* node1=malloc(sizeof(NODE));
node1->a=a;
node1->b=b;
node1->next=NULL;
return node1;
}
void printList()
{
NODE *ptr=NULL;
while(ptr!=NULL){
printf("%d", ptr->a);
printf("%d", ptr->b);
ptr = ptr->next;
}
}
int main()
{
NODE *head = malloc(sizeof(NODE));
head->next=NULL;
makenode();
printList();
return 0;
}
makenode() return type is void, it should be NODE*.
printList() does not fech the list so it can't know what to print, moreover ptr is NULL so it never enters the print loop.
Fixed code with comments:
Live demo
#include <stdlib.h>
#include <stdio.h>
typedef struct Node {
int a, b;
struct Node *next;
} NODE;
NODE* makenode() { //return type NODE*
NODE *node1 = malloc(sizeof(*node1));
printf("enter the name : ");
scanf("%d", &node1->a);
printf("enter the sur name : ");
scanf("%d", &node1->b);
node1->next = NULL;
return node1;
}
void printList(const NODE *ptr) { //pass NODE* ptr as an argument
int i = 1;
while (ptr != NULL) {
printf("Node %d\n", i++);
printf("a: %d\n", ptr->a);
printf("b: %d\n", ptr->b);
ptr = ptr->next;
}
}
int main() {
//make first node
NODE *head = makenode(); //assing node
// add one more node
NODE* node = makenode();
head->next = node; //chain second node
printList(head); //print nodes
return EXIT_SUCCESS;
}
On another note:
It's kind of strange that the names are int and not strings.
You could do:
Live demo
typedef struct Node {
char name[100]; //names as strings
char surname[100];
struct Node *next;
} NODE;
NODE* makenode() { //return type NODE*
NODE *node1 = malloc(sizeof(*node1));
printf("enter the name : ");
scanf(" %99[^\n]", node1->name);
printf("enter the sur name : ");
scanf(" %99[^\n]", node1->surname);
node1->next = NULL;
return node1;
}
void printList(const NODE *ptr) { //pass NODE* ptr as an argument
int i = 1;
while (ptr != NULL) {
printf("Node %d\n", i++);
printf("Name: %s\n", ptr->name);
printf("Surname: %s\n", ptr->surname);
ptr = ptr->next;
}
}
//...
//main is the same

C program reversed linked list

Im trying to write a program in c that adds big numbers with linked list. I used reverse to add the numbers, but i cant get it to reverse again. It should be used several times(iow, looped to ask numbers until exit)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "function.c"
int main()
{
char n1[500];
int lenSum, len;
printf("Welcome! \nThis program performs addition of big whole numbers that can contain upto a maximum of 500 digits.");
printf("\nEnter first number: ");
scanf("%s", n1);
len = strlen(n1);
node *root = create(n1[0]);
node *head = root;
root, head = createList(n1,root,head,len);
root=head;
printf("Enter second number: ");
scanf("%s", n1);
len = strlen(n1);
node *root2 = create(n1[0]);
node *head2 = root2;
root2, head2 = createList(n1,root2,head2,len);
root2=head2;
root=head;
printf("\nYour first number is:\t ");
while(root!=NULL){
printf("%d\t",root->digit);
root=root->next;
}
root2=head2;
printf("\nYour second number is: ");
while(root2!=NULL){
printf("%d\t",root2->digit);
root2=root2->next;
}
printf("\nCalculating sum:\n");
root=head;
root2=head2;
node *sum = create('0');
node *headSum = sum;
sum,headSum = addIntegers(root, root2, sum, headSum);
printf("\nThe sum is : ");
sum=headSum;
while(sum->next!=NULL){
printf("%d",sum->digit);
sum=sum->next;
}
printf("\n");
sum = headSum;
printf("\nThe number ");
saveResult(sum);
printf("has been saved in the file 'results.txt'\n");
root, head = reverseLinkedList(sum, headSum);
printDigit(root);
root=head;
printf("\n\n\t ");
while(root!=NULL){
printf("%d\t",root->digit);
root=root->next;
}
free(root);
free(root2);
//free(sumDigit);//
return 0;
}
function.h:
#ifndef function.h
#define function.h
typedef struct node {
int digit;
struct node *next;
}node;
node* create(char digit);
node* createList(char number[500], node* root,node* head, int length);
node* addIntegers(node* root, node* root2, node* sum, node* headSum);
#endif
function.c:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "function.h"
node* createList(char number[500], node* root,node* head, int length){
int i;
i=0;
for(i=1;i<=length-1;i++) {
root = (node *)malloc(sizeof(node));
root->digit = number[i]-'0';
root->next = head;
head = root;
}
return root, head;
}
void printDigit(node* root){
while(root!=NULL){
printf("%d",root->digit);
root=root->next;
}
}
node* addIntegers(node* root, node* root2, node* sum, node* headSum){
int carry = 0;
int sumDigit = 0;
while((root!=NULL || root2!=NULL)) {
if (root==NULL || root2==NULL){
if (root == NULL){
sumDigit=root2->digit +carry;
root2=root2->next;
goto add;}
if (root2 == NULL){
sumDigit = root->digit + carry;
root=root->next;
goto add;
}
}
else{
sumDigit = root->digit + root2-> digit + carry;
}
root2 = root2->next;
root = root->next;
add:
sum = (node *)malloc(sizeof(node));
sum->digit = sumDigit%10;
sum->next = headSum;
headSum = sum;
if (sumDigit > 9){
carry = 1;}
else{
carry = 0;
}
}
if (carry == 1){
sum = (node *)malloc(sizeof(node));
sum->digit = 1;
sum->next = headSum;
headSum = sum;
}
return sum, headSum;
}
node* create(char digit)
{
node *root = (node *) malloc( sizeof(node));
if (root == NULL){
printf("ERROR\n");
exit(1);
}
root->digit = digit-'0';
root->next = NULL; //default is null
return root;
}
void saveResult(struct node *sum)
{
FILE * fp = fopen ("result.txt", "w+");
while(sum->next != NULL)
{
printf("%d", sum->digit);
fprintf(fp, "%d", sum->digit);
sum = sum->next;
}
fclose(fp);
printf(" ");
}
node* reverseLinkedList(node *root, node* head){
node* reversed = create(root->digit);
node* reversedTail = reversed;
while(root!=NULL){
//printf("%d", root->digit);
root = root->next;
reversed->digit = root;
reversed->next =head->next;
reversed = reversed->next;
head = root;
}
reversed = reversedTail;
return reversed, reversedTail;
}
As the question is not very specific with the issue you're are facing, below are some points to be taken care,
In function reverse(),
return reversed, reversedTail; will always return reversedTail.
You are trying to call this function from main() as
root, head = reverseLinkedList(sum, headSum); which again head will get the return values. This is incorrect. Usually you should be using a assignment to one member at a time.
link list reverse sample like this
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int digit;
struct node *next;
} node;
node *reverse_copy(node *list){
node *new_list = NULL;
while(list){
node *new_node = malloc(sizeof(node));
new_node->digit = list->digit;
new_node->next = new_list;
new_list = new_node;
list = list->next;
}
return new_list;
}
void reverse_not_copy(node **header){
node *tmp, *list, *newList = NULL;
if (header==NULL || *header == NULL) return;
list = *header;
while(list != NULL){
tmp = list;
list = list->next;
tmp->next = newList;
newList = tmp;
}
*header = newList;
}
void print(node *head){
while(head){
printf("%d ", head->digit);
head = head->next;
}
printf("\n");
}
int main(void){
node *np;
node n[3] = { {1,NULL}, {2, NULL}, {3, NULL}};
n[0].next = &n[1];
n[1].next = &n[2];
print(&n[0]);//1 2 3
np=reverse_copy(&n[0]);
print(np);//3 2 1
reverse_not_copy(&np);
print(np);//1 2 3
return 0;
}

Why does this linked-list ordered insert segfault?

I am working on a program that inserts into a linked-list in sorted order, but it keeps seg faulting, and I can't figure out why. I suspect it has something to do with the pointers, but I can't tell as these are still a little bit confusing to me at this point in my programming career. Also, I must keep the insert prototype the same. I can't change the node parameter into a double pointer. Thanks!
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<conio.h>
typedef struct node {
int data;
struct node *next;
};
int main ()
{
struct node* first;
int temp,x,y;
struct node *create (struct node *first);
first = NULL;
void display (struct node *first);
printf ("\n\nCreating a Linked List\n");
printf ("\nEnter Element: ");
scanf ("%d", &x);
y=x;
while(y>0)
{
scanf ("%d", &x);
insert_sorted_linked_list(first,x);
y--;
}
printf ("\nThe list after creation is: ");
display (first);
printf ("\nThe sorted list is: ");
display (first);
return(0);
} /*END OF MAIN*/
insert_sorted_linked_list(struct node* head, int val)
{
struct node* pCur;
struct node* pNew = (struct node*) (malloc(sizeof(struct node)));
pNew -> data = val;
pNew ->next = NULL;
pCur = head;
if( pCur->data == NULL )
{
head->data = pNew->data;
head->next = NULL;
}
else if (pNew->data < pCur->data)
{
pNew ->next = pCur ;
head = pNew;
}
}
void display (struct node *first)
{ struct node *save; /*OR sort *save */
if (first == NULL)
printf ("\nList is empty");
else
{ save = first;
while (save != NULL)
{ printf ("-> %d ", save->data);
save = save->next;
}
getch();
}
return;
}
EDIT: Changed main to int. The debugger doesn't like the lines:
struct node* pNew = (struct node*) (malloc(sizeof(struct node)));
if( pCur->data == NULL )
Not sure what is wrong though.
EDIT 2:
I decided i wasn't going to get it working the original way he ask for it before tomorrow morning, so I went a modified version posted here. That one didn't seg fault, but it turns out there was a logic error as well.
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<conio.h>
typedef struct s
{
int data;
struct s *next;
}node;
void insert_sorted_linked_list(node **head, int val);
void display (node **first);
void freeList(node **first);
int main ()
{
node* first;
int x,y;
first = NULL;
printf ("\n\nCreating a Linked List\n");
printf ("\nEnter number of elements: ");
scanf ("%d", &x);
y=x;
while(y>0)
{
scanf ("%d", &x);
insert_sorted_linked_list(&first,x);
y--;
}
printf ("\nThe sorted list is: ");
display (&first);
freeList(&first);
return 0;
}
void insert_sorted_linked_list(node **head, int val)
{
node* pCur;
node* pNew = (node*) (malloc(sizeof(node)));
pNew->data = val;
pNew->next = NULL;
pCur = (*head);
if( pCur == NULL )
{
(*head) = pNew;
}
else if(pNew->data < pCur->data)
{
pNew->next = pCur;
(*head) = pNew;
}
else
{
while(pCur->next!=NULL && pNew->data > pCur->next->data)
pCur = pCur->next;
pNew->next = pCur->next;
pCur->next = pNew;
}
}
void display (node **first)
{
node *lisprint; /*OR sort *lisprint */
if (*first == NULL)
printf ("\nList is empty");
else
{
lisprint = *first;
while (lisprint != NULL)
{
printf ("-> %d ", lisprint->data);
lisprint = lisprint->next;
}
getch();
}
} /*END OF FUNCTION DISPLAY*/
void freeList(node **first)
{
node *i;
i = *first;
while(i !=NULL)
{
(*first) = (*first)->next;
free(i);
i = *first;
}
}
Thanks!
Please properly format your code! It was a pain in the a** just to see where the error was!
As it is,
/*PROGRAM TO CREATE & THEN DISPLAY THE LINKED LIST IN SORTED FORM*/
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<conio.h>
typedef struct s
{
int data;
struct s *next;
}node;
/* your declaration for typedef was incorrect. We use typedef in C for structures so that we do not have to repeat struct s everytime. Using typedef, we can write node as we do in c++ */
void insert_sorted_linked_list(node **head, int val); /* do not need to return anything, as well as see the parameter. When we want to change a pointer, we pass the address to the pointer, as it results in passing by value */
void display (node **first); /* same here and below */
void freeList(node **first); /* if you don't do this, memory leak!!! */
int main ()
{
node* first; /*OR sort *first,*list,*pass */
int temp,x,y;
first = NULL; /*OR sort *create() */
printf ("\n\nCreating a Linked List\n");
printf ("\nEnter number of elements: "); /* specify what you want the user to enter */
scanf ("%d", &x);
y=x;
while(y>0)
{
scanf ("%d", &x);
insert_sorted_linked_list(&first,x); /*CALLING CREATE FUNCTION, notice the &first*/
y--;
}
printf ("\nThe list after creation is: ");
display (&first);
printf ("\nThe sorted list is: ");
display (&first);
freeList(&first);
return 0;
} /*END OF MAIN*/
void insert_sorted_linked_list(node **head, int val)
{
node* pCur;
node* pNew = (node*) (malloc(sizeof(node)));
pNew->data = val;
pNew->next = NULL;
pCur = (*head);
if( pCur == NULL )
{
(*head) = pNew;
}
else if (pNew->data < pCur->data)
{
pNew->next = pCur ;
(*head) = pNew;
}
}
/*DISPLAY FUNCTION*/
void display (node **first)
{
node *save; /*OR sort *save */
if (*first == NULL)
printf ("\nList is empty");
else
{
save = *first;
while (save != NULL)
{
printf ("-> %d ", save->data);
save = save->next;
}
getch();
}
} /*END OF FUNCTION DISPLAY*/
void freeList(node **first)
{
node *i;
i = *first;
while(i !=NULL)
{
(*first) = (*first)->next;
free(i);
i = *first;
}
}

Resources