加一链表
题目:
描述
给定一个非负整数,这个整数表示为一个非空的单链表,
每个节点表示这个整数的一位。返回这个整数加一。
除了0本身,所有数字在最高位前都没有0。
列表的头节点存的是这个整数的最高位。
样例
样例1
输入: 1 -> 2 -> 3 -> null
输出: 1 -> 2 -> 4 -> null
解释:
123 + 1 = 124
样例2
输入: 9 -> 9 -> null
输出: 1 -> 0 -> 0 -> null
解释:
99 + 1 = 100
解题思路:本题有两种思路,一种是用栈存储每个节点后进行加一操作,另一种是利用递归
栈:
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: the first Node
* @return: the answer after plus one
*/
public ListNode plusOne(ListNode head) {
if(head == null) {
return null;
}
Stack<ListNode> stack = new Stack();
ListNode cur = head;
while(cur != null) {
stack.push(cur);
cur = cur.next;
}
ListNode tail = stack.pop();
tail.val += 1;
boolean flag = false;
if(tail.val >= 10) {
tail.val -= 10;
flag = true;
}
while(flag && !stack.isEmpty()) {
ListNode node = stack.pop();
node.val += 1;
if(node.val >= 10) {
node.val -= 10;
flag = true;
} else {
flag = false;
}
}
if(stack.isEmpty() && flag) {
ListNode first = new ListNode(1);
first.next = head;
head = first;
}
return head;
}
}
递归:
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: the first Node
* @return: the answer after plus one
*/
private int flag = 0;
public ListNode plusOne(ListNode head) {
// Write your code here
if(head == null) {
return null;
}
head = dfs(head);
if(flag == 1) {
ListNode node = new ListNode(1);
node.next = head;
head = node;
}
return head;
}
public ListNode dfs(ListNode head) {
if(head == null) {
return null;
}
if(head.next == null) {
head.val += 1;
if(head.val >= 10) {
head.val -= 10;
flag = 1;
}
return head;
}
head.next = dfs(head.next);
if(flag == 1) {
head.val += 1;
flag = 0;
}
if(head.val >= 10) {
head.val -= 10;
flag = 1;
}
return head;
}
}