Input:
1->2->3
Output:
1->2->4
1,反转后从左向右加一,当最高位出现进位的时候,额外申请一个节点保存进位,之后在反转链表并返回。
2,当没有进位的适合不需要继续遍历链表
3,在遍历链表做加一的同时,记录下当前节点的前一个节点,当循环退出条件是p==NUll适合,同时又存在最高位有进位的情况,需要prev指针指向这个进位节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
struct ListNode *node;
node = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return node;
}
struct ListNode* plusOne(struct ListNode* head) {
struct ListNode *head1, *head2;
struct ListNode *p,*prev;
int val;
if(head == NULL )
return NULL;
head1 = reverseList(head);
p = head1;
val = p->val +1;
p->val = val%10;
int carry = val/10;
prev = p;
p = p->next;
while(p&&carry){
val = p->val+carry;
p->val = val%10;
carry = val/10;
prev = prev->next;
p = p->next;
}
if(carry){
printf("++");
struct ListNode *node = malloc(sizeof(struct ListNode));
node->val = carry;
node->next = NULL;
prev->next = node;
}
head2 = reverseList(head1);
return head2;
}
struct ListNode* plusOne(struct ListNode* head) {
struct ListNode *head1, *head2;
struct ListNode *p,*prev;
int val;
if(head == NULL )
return NULL;
head1 = reverseList(head);
p = head1;
val = p->val +1;
p->val = val%10;
int carry = val/10;
prev = p;
p = p->next;
while(p&&carry){
val = p->val+carry;
p->val = val%10;
carry = val/10;
prev = prev->next;
p = p->next;
}
if(carry){
printf("++");
struct ListNode *node = malloc(sizeof(struct ListNode));
node->val = carry;
node->next = NULL;
prev->next = node;
}
head2 = reverseList(head1);
return head2;
}