# https://space.bilibili.com/206214 classSolution: # 206. 反转链表 # 视频讲解 https://www.bilibili.com/video/BV1sd4y1x7KN/ defreverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: pre = None cur = head while cur: nxt = cur.next cur.next = pre pre = cur cur = nxt return pre
// 206. 反转链表 // 视频讲解 https://www.bilibili.com/video/BV1sd4y1x7KN/ funcreverseList(head *ListNode) *ListNode { var pre, cur *ListNode = nil, head for cur != nil { nxt := cur.Next cur.Next = pre pre = cur cur = nxt } return pre }
funcdoubleIt(head *ListNode) *ListNode { head = reverseList(head) res := double(head) // 反转后,就变成【2. 两数相加】了 return reverseList(res) }
复杂度分析
时间复杂度:\mathcal{O}(n),其中 n 为链表的长度。
空间复杂度:\mathcal{O}(1)。返回值不计入。
方法二
如果不考虑进位,就是每个节点的值乘以 2。
什么时候会受到进位的影响呢?只有下一个节点大于 4 的时候,才会因为进位多加一。
特别地,如果链表头的值大于 4,那么需要在前面插入一个新的节点。
[sol-Python3]
1 2 3 4 5 6 7 8 9 10 11
classSolution: defdoubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]: if head.val > 4: head = ListNode(0, head) cur = head while cur: cur.val = cur.val * 2 % 10 if cur.nextand cur.next.val > 4: cur.val += 1 cur = cur.next return head
[sol-Java]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public ListNode doubleIt(ListNode head) { if (head.val > 4) head = newListNode(0, head); for (varcur= head; cur != null; cur = cur.next) { cur.val = cur.val * 2 % 10; if (cur.next != null && cur.next.val > 4) cur.val++; } return head; } }
[sol-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: ListNode *doubleIt(ListNode *head){ if (head->val > 4) head = newListNode(0, head); for (auto cur = head; cur; cur = cur->next) { cur->val = cur->val * 2 % 10; if (cur->next && cur->next->val > 4) cur->val++; } return head; } };
[sol-Go]
1 2 3 4 5 6 7 8 9 10 11 12
funcdoubleIt(head *ListNode) *ListNode { if head.Val > 4 { head = &ListNode{0, head} } for cur := head; cur != nil; cur = cur.Next { cur.Val = cur.Val * 2 % 10 if cur.Next != nil && cur.Next.Val > 4 { cur.Val++ } } return head }