369. Plus One Linked List

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.