Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use leetcode to realize the summation of linked list in golang

Shulou Source: shulou.com Published: 2022-06-02 07:45:01 09月27日 Update

This article shows you how to use leetcode to achieve the sum of linked lists in golang. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Given two integers represented by a linked list, each node contains a digit.

These digits are stored in reverse, that is, one bit at the beginning of the linked list.

Write a function to sum the two integers and return the results in a linked list.

Example:

Enter: (7-> 1-> 6) + (5-> 9-> 2), that is, 617 + 295

Output: 2-> 1-> 9, i.e. 912

Advanced: assuming that these digits are stored in the forward direction, please do it again.

Example:

Enter: (6-> 1-> 7) + (2-> 9-> 5), that is, 617 + 295

Output: 9-> 1-> 2, i.e. 912

Problem-solving ideas

1, this topic needs to pay attention to a detail, carry mark

2, there is a position in front of each position, so it is relatively simple

3. It should be noted that the length of the two linked lists is not the same.

4, special treatment is required for the case of 1: 9999

Code implementation

/ * Definition for singly-linked list. * type ListNode struct {* Val int * Next * ListNode * * / func addTwoNumbers (L1 * ListNode, L2 * ListNode) * ListNode {if l1==nil {return L2} if l2==nil {return L1} r:=new (ListNode) tr:=r t1:=l1 t2:=l2 flag:=0

Tr.Val= (t1.Val+t2.Val+flag) flag= (t1.Val+t2.Val+flag) / 10 for t1.NextEntropnil & & t2.NextFortunnil {tr.Next=new (ListNode) tr=tr.Next t1=t1.Next t2=t2.Next

Tr.Val= (t1.Val+t2.Val+flag) flag= (t1.Val+t2.Val+flag) / 10}

For t1.NextDiagnil {tr.Next=new (ListNode) tr=tr.Next t1=t1.Next tr.Val= (t1.Val+flag) flag= (t1.Val+flag) / 10}

For t2.NextDiagnil {tr.Next=new (ListNode) tr=tr.Next t2=t2.Next tr.Val= (t2.Val+flag) flag= (t2.Val+flag) / 10}

If benchmark 0 {tr.Next=new (ListNode) tr=tr.Next tr.Val=flag}

Return r} the above is how to use leetcode to achieve linked list summation in golang. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Two digital individual content skills integers knowledge examples input output special concise consistent concise to the point that is code function that is form idea Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info MySQL Linux macOS Redmi