题解 | #给单链表加一#
给单链表加一
http://www.nowcoder.com/practice/a2f1105d2ac5466e9ba8fd61310ba6d1
package main import . "nc_tools" /*
- type ListNode struct{
- Val int
- Next *ListNode
- } */
/**
- 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
- @param head ListNode类
- @return ListNode类 */ func plusOne( head *ListNode ) *ListNode { // write code here dumny := &ListNode{Next: head} root := f(dumny) if root.Val > 0 { return root }else{ return root.Next } }
//后序遍历 func f(head *ListNode) *ListNode { // write code here if head.Next == nil { head.Val += 1 return head } next := f(head.Next) if next.Val > 9 { head.Val+= 1 next.Val = next.Val - 10 } return head }