您的位置:首页 > 其它

Plus One Linked List

2016-08-03 00:44 357 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: