Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active October 5, 2017 14:30
Show Gist options
  • Save cixuuz/b2349d0c62481f3b9f64f872a1515590 to your computer and use it in GitHub Desktop.
Save cixuuz/b2349d0c62481f3b9f64f872a1515590 to your computer and use it in GitHub Desktop.
[369. Plus One Linked List] #leetcode
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode plusOne(ListNode head) {
if (head == null) return null;
ListNode pre = null;
ListNode cur = head;
// reverse linkedlist to the end node
while (cur != null && cur.next != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
// add one
int carry = 1;
// reverse back
while (pre != null) {
cur.val += carry;
carry = cur.val / 10;
cur.val = cur.val % 10;
ListNode beforePre = pre.next;
pre.next = cur;
cur = pre;
pre = beforePre;
}
if (carry > 0) {
cur.val += carry;
carry = cur.val / 10;
cur.val = cur.val % 10;
if (carry > 0) {
ListNode newHead = new ListNode(carry);
newHead.next = head;
head = newHead;
}
}
return head;
}
}
class Solution1 {
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);
int val = head.val + carry;
head.val = val%10;
return val/10;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment