一.题目描述
用一个非空单链表来表示一个非负整数,然后将这个整数加一。 你可以假设这个整数除了 0 本身,没有任何前导的 0。 这个整数的各个数位按照高位在链表头部、低位在链表尾部的顺序排列。 示例: 输入: [1,2,3] 输出: [1,2,4]
二.代码
public ListNode plusOne(ListNode head) {
ListNode fastPoint = head;
ListNode slowPoint = new ListNode(0);
slowPoint.next = head;
while (null != fastPoint){
if (fastPoint.val != 9) {
slowPoint = fastPoint;
}
fastPoint = fastPoint.next;
}
slowPoint.val++;
ListNode curr = slowPoint.next;
while (null != curr) {
curr.val=0;
curr = curr.next;
}
return slowPoint.next == head ? slowPoint : head;
}
public ListNode plusOne(ListNode head) {
head = reverse(head);
ListNode p = head;
while (p != null) {
if (p.val + 1 <= 9) {
p.val = p.val + 1;
break;
} else {
p.val = 0;
if (p.next == null) {
p.next = new ListNode(1);
break;
}
p = p.next;
}
}
return reverse(head);
}
public ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}