2020年3月19日 星期四

LeetCode #2 Add Two Numbers [ C language ] [ Medium ]

今天這題蠻有趣的,想練習 Link List 的朋友可以試試看,終於知道為甚麼資料結構一直都學不好了,因為在學生成樹之前,基本觀念都還不清楚啊,用筆畫那些樹和用程式語言去實現差別實在是太大了,所幸藉由這題把以往的記憶都找回來了,繼續加油。

This is a basic problem using link list, if you don't know the concept of pointer and function, try to solve it on LeetCode problem #2.




/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *newNode(int data) { struct ListNode *NewNode = (struct ListNode *) malloc(sizeof(struct ListNode)); NewNode->val = data; NewNode->next = NULL; return NewNode; } struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){ struct ListNode *answer = NULL; int sum=0,tmp; int carry=0; answer=newNode(0); struct ListNode *end =answer; while(l1!=NULL ||l2!=NULL || carry>0){ tmp=(l1?l1->val:0)+(l2?l2->val:0); if(carry==1) tmp=tmp+1; carry=(tmp>=10)?1:0; tmp=(tmp>=10)?(tmp-10):tmp; answer->next= newNode(tmp); if(l1) l1=l1->next; if(l2) l2=l2->next; answer=answer->next; } return end->next; }

沒有留言:

張貼留言

 2025 MTK 韌體工程師 上機考心得  前言: 以前, 我覺得寫前後端的人才是真正的寫程式, 很羨慕那些大神 直到這次準備, 我才發現靠杯, 原來寫底層的程式也那麼硬派, XOR 一些奇奇怪怪的加速運算操作, 剛看到真的是無法想像, 有夠虧賊!   1. C/C++ Pro...