题目描述:
给定一个非负整数,这个整数表示为一个非空的单链表,每个节点表示这个整数的一位。返回这个整数加一。
除了0本身,所有数字在最高位前都没有0。
列表的头节点存的是这个整数的最高位。
样例:
给出链表1 -> 2 -> 3 -> null
,返回 1 -> 2 -> 4 -> null
。
思路:看到这个每个节点表示一位,主要难点在于链表表示的是从高位到低位的,而进行加一操作时是低位操作的,还存在进位问题,还有多出一位的情况,例如99,9999... 所以首先将链表倒转一下,表示成从低位指向高位,这样加一操作就可以从表头开始,当存在进位时,就看下一个节点,知道某一位没有进位,另一种情况直到链表尾部还是有进位,需要多生成一个节点表示最高位。所有操作都完成以后,返回之前,将链表倒转回来,返回头结点。
代码:
ListNode* reverseList(ListNode* head){
if(head == NULL || head->next==NULL)
return head;
ListNode* slow = head;
ListNode* mid = head->next;
ListNode* fast = mid->next;
slow->next = NULL;
while(fast){
mid->next = slow;
slow = mid;
mid = fast;
fast = fast->next;
}
mid->next = slow;
return mid;
}
ListNode * plusOne(ListNode * head) {
// Write your code here
if(head == NULL)
return head;
if(head->next == NULL){
int tmp = head->val;
if(tmp < 9){
head->val += 1;
return head;
}
else{
head->val = 1;
head->next = new ListNode(0);
return head;
}
}
//至少两位数,先翻转链表,在执行加一操作
ListNode* rhead = reverseList(head);
int res = (rhead->val + 1) % 10;
int cnt = (rhead->val + 1) / 10;
rhead->val = res;
ListNode* ite = rhead->next;
ListNode* pre = rhead;
while(cnt && ite){
int cnttmp = (ite->val + cnt) /10;
ite->val = (ite->val + cnt) % 10;
cnt = cnttmp;
pre = ite;
ite = ite->next;
}
if(cnt){
pre->next = new ListNode(1);
}
return reverseList(rhead);
}