Given a non-negative number represented as a singly linked list of digits, plus one to the number.
The digits is stored such, the most significant digit was at the head of the list.
Example:
Input:1->2->3output:1->2->4
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode PlusOne (ListNode head) {if(Head = =NULL)returnHead; ListNode l=NewListNode (0); ListNode Dummy=l; ListNode Rehead=Reverselist (head); intCarry = 1; intDigit = 0; ListNode cur=Rehead; while(cur! =NULL|| Carry! = 0){ intIndex = (cur = =NULL)? 0: Cur.val; Digit= (index + carry)% 10; Carry= (index + carry)/10; L.next=NewListNode (digit); L=L.next; if(cur! =NULL) cur=Cur.next; } returnreverselist (Dummy.next); } PublicListNode reverselist (ListNode head) {if(Head = =NULL|| Head.next = =NULL)returnHead; ListNode Dummy=NewListNode (0); Dummy.next=Head; ListNode cur=Head.next; while(cur! =NULL) {Head.next=Cur.next; Cur.next=Dummy.next; Dummy.next=cur; Cur=Head.next; } returnDummy.next; }}
369. Plus One Linked List