码迷,mamicode.com
首页 > 其他好文 > 详细

Plus One Linked List

时间:2016-08-03 01:24:13      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

Given a non-negative number represented as a singly linked list of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

Example:

Input:
1->2->3

Output:
1->2->4

解法一:reverse
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode plusOne(ListNode head) {
        head = reverse(head);
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode x = dummy;
        int carry = 1;
        while (carry > 0 || x.next != null) {
            if (x.next != null) {
                x = x.next;
                carry += x.val;
                x.val = carry % 10;
                carry /= 10;
            }
            else {
                x.next = new ListNode(carry);
                x = x.next;
                carry = 0;
            }
        }
        return reverse(dummy.next);
    }
    
    public ListNode reverse(ListNode head){
        if (head == null) return head;
        ListNode pre = null;
        ListNode cur = head;
        while(cur.next!=null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        cur.next = pre;
        return cur;
    }
}

reference: https://discuss.leetcode.com/topic/49647/reverse-plus-one-then-reverse

 

解法二:寻找从右边到左边的第一个非9的node

public ListNode plusOne(ListNode head) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode runner = dummy;
    ListNode pointer = dummy; //from right to left, find the first digit that is not 9;
    
    while(runner.next != null) {
        runner = runner.next;
        if(runner.val != 9) pointer = runner;
    }
    
    pointer.val = pointer.val + 1;
    runner = pointer.next;
    while(runner != null) {
        runner.val = 0;
        runner = runner.next;
    }
    
    return pointer == dummy? dummy : head;
}

reference:https://discuss.leetcode.com/topic/49867/concise-java-iterative-solution

 

解法三:DFS

public ListNode plusOne(ListNode head) {
    if( DFS(head) == 0){
        return head;
    }else{
        ListNode newHead = new ListNode(1);
        newHead.next = head;
        return newHead;
    }
}

public int DFS(ListNode head){
    if(head == null) return 1;
    
    int carry = DFS(head.next);
    
    if(carry == 0) return 0;
    
    int val = head.val + 1;
    head.val = val%10;
    return val/10;
}

reference: https://discuss.leetcode.com/topic/49541/java-recursive-solution

Plus One Linked List

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5731295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!