列表反向组成数字相加,并输出数组反向组成列表
生活随笔
收集整理的這篇文章主要介紹了
列表反向组成数字相加,并输出数组反向组成列表
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
# Definition for singly-linked list.
#在節(jié)點(diǎn)ListNode定義中,定義為節(jié)點(diǎn)為結(jié)構(gòu)變量。
#節(jié)點(diǎn)存儲(chǔ)了兩個(gè)變量:value 和 next。value 是這個(gè)節(jié)點(diǎn)的值,next 是指向下一節(jié)點(diǎn)的指針,當(dāng) next 為空指針時(shí),這個(gè)節(jié)點(diǎn)是鏈表的最后一個(gè)節(jié)點(diǎn)。
#注意注意val只代表當(dāng)前指針的值,比如p->val表示p指針的指向的值;而p->next表示鏈表下一個(gè)節(jié)點(diǎn),也是一個(gè)指針。
#構(gòu)造函數(shù)包含兩個(gè)參數(shù) _value 和 _next ,分別用來(lái)給節(jié)點(diǎn)賦值和指定下一節(jié)點(diǎn)
class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = next
class Solution:def listnode_reversal(self,head:ListNode)->ListNode:print("開(kāi)始反轉(zhuǎn)")# head頭節(jié)點(diǎn),判斷頭節(jié)點(diǎn)是否為空,或者是否只存在一個(gè)節(jié)點(diǎn)if (head == None or head.next == None):return head;# 創(chuàng)建一個(gè)節(jié)點(diǎn)d = ListNode(-1)# 對(duì)于頭節(jié)點(diǎn)來(lái)說(shuō)相當(dāng)于前面加了一個(gè)空的節(jié)點(diǎn)d.next = head# 定義前一節(jié)點(diǎn)指針,當(dāng)前節(jié)點(diǎn)指針,輔助指針(后一節(jié)點(diǎn)指針)# pre節(jié)點(diǎn)一直都沒(méi)有變pre = dcur = head# 讓鏈表結(jié)構(gòu)反轉(zhuǎn)while (cur != None and cur.next != None):tmp = cur.next # 用于保存當(dāng)前節(jié)點(diǎn)指針cur的后一節(jié)點(diǎn)指針cur.next = tmp.next # 更新cur指針tmp.next = pre.next # 將當(dāng)前節(jié)點(diǎn)指針cur后一節(jié)點(diǎn)的指針指向cur(即指針指向順序顛倒)pre.next = tmp # 更新pre指針return d.nextdef listnode_to_number(self,head)->int:if (head == None or head.next == None):return 0;# 計(jì)數(shù)sum = 1#數(shù)字resultnumber = 0while head != None:resultnumber = resultnumber + head.val * (10 ** sum)print("相加%d" % (resultnumber))sum = sum + 1head = head.nextreturn resultnumberdef addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:#反轉(zhuǎn)列表l1 = self.listnode_reversal(l1)l2 = self.listnode_reversal(l2)#返回列表組成的數(shù)字resultl1 = self.listnode_to_number(l1)resultl2 = self.listnode_to_number(l2)print("l1倒敘組成的數(shù)字為%d"%(resultl1))print("l2倒敘組成的數(shù)字為%d" % (resultl2))resultsum = resultl1 + resultl2print("相加數(shù)字為%d" % (resultsum))#存放結(jié)果類型resultlistnodehead = ListNode(0)first_pointer = resultlistnodehead#結(jié)果的字符串類型strresult = str(resultsum)for k in strresult[::-1]:newnode = ListNode(int(k))resultlistnodehead.next = newnoderesultlistnodehead = newnodeprint(first_pointer.next.val)print(first_pointer.next.next.val)print(first_pointer.next.next.next.val)print(first_pointer.next.next.next.next.val)print(first_pointer.next.next.next.next.next.val)return first_pointer.nextl1 = ListNode(0);
l1_1 = ListNode(1);
l1.next = l1_1;
l1_2 = ListNode(2);
l1_1.next = l1_2;
l1_3 = ListNode(3);
l1_2.next = l1_3;
l1_4 = ListNode(4);
l1_3.next = l1_4;l2 = ListNode(0);
l2_1 = ListNode(1);
l2.next = l2_1;
l2_2 = ListNode(2);
l2_1.next = l2_2;
l2_3 = ListNode(3);
l2_2.next = l2_3;
l2_4 = ListNode(4);
l2_3.next = l2_4;
S = Solution()
print(S.addTwoNumbers(l1,l2))
總結(jié)
以上是生活随笔為你收集整理的列表反向组成数字相加,并输出数组反向组成列表的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 套现行为违法吗?套现的真实面目!
- 下一篇: 中信信用卡可以还京东白条吗?怎么还款?