leetcode2 Add Two Numbers 方法2
思路:凡是对链表的数字的操作,都可以考虑将这些数字转化为一个long或者一个数组(这个思路较好,可以为以后的开发省去好多不必要的步骤)
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
这个方法就是将链表中的数字串起来,当做一个long,例如2->4->5,可以根据题目具体要求转化成long型的245或542,再做后续的操作,就很容易了。举一反三,链表数字的反序也可以采用这个方法。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public Long listTOLong(ListNode l){ 14 long num = 0; 15 long temp =1; 16 int i=0; 17 while(l!=null){ 18 num = num+l.val*temp; 19 temp=temp*10; 20 l=l.next; 21 } 22 return num; 23 } 24 public ListNode longToList(Long num){ 25 ListNode l3 = new ListNode(-1); 26 l3.next = null; 27 ListNode c = l3; 28 c.val=(int)(num%10); 29 num = num/10; 30 while(num>0){ 31 ListNode cnext = new ListNode((int)(num%10)); 32 cnext.next=null; 33 c.next=cnext; 34 num = num/10; 35 c=c.next; 36 } 37 return l3; 38 } 39 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 40 if(l1==null&&l2==null){ 41 return null; 42 } 43 //链表转long型 44 long num1 = listTOLong(l1); 45 long num2 = listTOLong(l2); 46 //System.out.println("l1:"+num1+" l2:"+num2); 47 long num3 = num1+num2; 48 //System.out.println("l3:"+num3); 49 //long型转链表 50 ListNode l3 = longToList(num3); 51 return l3; 52 53 } 54 }
还可以利用结构体的方法
1 struct ListNode { 2 int val; 3 ListNode *next; 4 ListNode(int x) : val(x), next(NULL) {} 5 }; 6 7 class Solution { 8 public: 9 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 10 // Start typing your C/C++ solution below 11 // DO NOT write int main() function 12 // ListNode *pResult = NULL; 13 // ListNode **pCur = &pResult; 14 15 ListNode rootNode(0); 16 ListNode *pCurNode = &rootNode; 17 int a = 0; 18 while (l1 || l2) 19 { 20 int v1 = (l1 ? l1->val : 0); 21 int v2 = (l2 ? l2->val : 0); 22 int temp = v1 + v2 + a; 23 a = temp / 10; 24 ListNode *pNode = new ListNode((temp % 10)); 25 pCurNode->next = pNode; 26 pCurNode = pNode; 27 if (l1) 28 l1 = l1->next; 29 if (l2) 30 l2 = l2->next; 31 } 32 if (a > 0) 33 { 34 ListNode *pNode = new ListNode(a); 35 pCurNode->next = pNode; 36 } 37 return rootNode.next; 38 } 39 };
浙公网安备 33010602011771号