链表-加一链表-中等

描述

给定一个非负整数,这个整数表示为一个非空的单链表,每个节点表示这个整数的一位。返回这个整数加一。

除了0本身,所有数字在最高位前都没有0。

列表的头节点存的是这个整数的最高位。

您在真实的面试中是否遇到过这个题?  是

样例

给出链表1 -> 2 -> 3 -> null,返回 1 -> 2 -> 4 -> null

题目链接

程序



/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: the first Node
     * @return: the answer after plus one
     */
    ListNode *reverseList(ListNode *head){
        ListNode *pre = NULL;
        ListNode *cur = head;
        while(cur){
            ListNode *tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
    ListNode * plusOne(ListNode * head) {
        // Write your code here
        head = reverseList(head);
        int tmp, c = 0;//c是存放十位数,tmp十位+个位
        ListNode *pre = head, *cur = head;
        //最低位+1
        tmp = 1 + cur->val;
        cur->val = tmp % 10;
        c = tmp/10;
        cur = cur->next;
        //剩下的位数不需要再+1
        while(cur){
            tmp = cur->val + c;
            cur->val = tmp % 10;
            c = tmp/10;
            cur = cur->next;
            pre = pre->next;
        }

        //最最高位非零,再加一位
        //cur当前为NULL,废了
        if(c != 0){
            ListNode *tmp1 = new ListNode(c);
            pre->next = tmp1;
            pre->next->next = NULL;
        }
        return reverseList(head);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_18124075/article/details/81109186
今日推荐