369 Plus One Linked List

需要先翻转链表

Python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        prev, curr = None, head
        while curr:
            t = curr.next
            curr.next = prev
            prev = curr
            curr = t
        return prev

    def plusOne(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        rev = self.reverseList(head)
        curr = rev
        carry = 1
        while curr:
            if carry == 0:
                break
            curr.val += carry
            carry = 0
            if curr.val > 9:
                carry = 1
                curr.val -= 10
            curr = curr.next
        if carry == 1:
            t = ListNode(1)
            t.next = self.reverseList(rev)
            return t
        else:
            return self.reverseList(rev)

Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head){
        ListNode prev = null, curr = head;
        while(curr != null){
            ListNode t = curr.next;
            curr.next = prev;
            prev = curr;
            curr = t;
        }
        return prev;
    }
    public ListNode plusOne(ListNode head) {
        ListNode rev = this.reverseList(head);
        ListNode cur = rev;
        int carry = 1;
        while(cur!= null){
            cur.val += carry;
            carry = 0;
            if(cur.val > 9){
                cur.val -= 10;
                carry = 1;
            }
            else{
                break;
            }
            cur = cur.next;
        }
        if(carry == 1){
            ListNode n = new ListNode(1);
            n.next = this.reverseList(rev);
            return n;
        }
        else{
            return this.reverseList(rev);
        }
    }
}

results matching ""

    No results matching ""