-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddOne.c
77 lines (71 loc) · 1.22 KB
/
AddOne.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
struct node* reverse(struct node* head)
{
struct node* prev=NULL;
struct node* next;
struct node* current=head;
while(current)
{
next=current->next;
current->next=prev;
prev=current;
current=next;
}
return prev;
}
void printList(struct node* head)
{
while(head)
{
printf("%d ",head->data);
head=head->next;
}
}
struct node* addOne(struct node* head)
{
int carry=1;
int sum=0;
struct node* res=head;
struct node* temp;
struct node* head1=reverse(head);
while(head1)
{
sum+=carry+head->data;
carry=(sum==10)?1:0;
sum=sum%10;
head->data=sum;
temp=head;
head=head->next;
}
if(carry>0)
{
temp->next=newNode(carry);
}
return (reverse(res));
}
struct node* newNode(int new_node)
{
struct node* temp=(struct node*)malloc(sizeof(struct node));
temp->data=new_node;
temp->next=NULL;
return temp;
}
int main(void)
{
struct node *head = newNode(1);
head->next = newNode(9);
head->next->next = newNode(9);
head->next->next->next = newNode(9);
printf("List is ");
printList(head);
head = addOne(head);
printf("\nResultant list is ");
printList(head);
return 0;
}