LeetCode刷题实战369:给单链表加一
Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
示例
输入: [1,2,3]
输出: [1,2,4]
解题
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode plusOne(ListNode head) {
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode curr = newHead;
ListNode curr_head = newHead;
while(curr.next!=null){
curr = curr.next;
if(curr.val != 9){
curr_head = curr;
}
}
if(curr_head == curr){
curr.val++;
}else{
curr_head.val++;
curr = curr_head;
while(curr.next != null){
curr = curr.next;
curr.val = 0;
}
}
if(newHead.val == 0){
newHead.next = null;
return head;
}else{
return newHead;
}
}
}