题解 | #给单链表加一#
给单链表加一
https://www.nowcoder.com/practice/a2f1105d2ac5466e9ba8fd61310ba6d1
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode plusOne (ListNode head) { // write code here if (head == null) return head; //倒序 ListNode ln = new ListNode(0); while (head != null) { ListNode lnT = ln.next; ln.next = head; head = head.next; ln.next.next = lnT; } ListNode lnTG = ln.next; int nAddc = 1; ListNode lnR = ln; lnR.next = null; while (lnTG != null) { int nT = lnTG.val; lnTG.val = (nT + nAddc) % 10; nAddc = (nT + nAddc) / 10; ListNode lnT = lnR.next; lnR.next = lnTG; ListNode lnTGN = lnTG.next; lnTG.next = lnT; lnTG = lnTGN; } if (nAddc > 0) { ln.val = 1; return ln; } else { return ln.next; } } }