LeetCode Online Judge 题目C# 练习 - Add two number
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
1 class LinkedListNode 2 { 3 public object Value; 4 public LinkedListNode Next; 5 6 public LinkedListNode() 7 { 8 this.Value = null; 9 this.Next = null; 10 } 11 12 public LinkedListNode(int value) 13 { 14 this.Value = value; 15 this.Next = null; 16 } 17 }
1 public static LinkedListNode AddTwoNumber(LinkedListNode n1, LinkedListNode n2) 2 { 3 LinkedListNode ret = new LinkedListNode(); 4 LinkedListNode cur = ret; 5 int carry = 0; 6 int sum; 7 8 while (n1 != null || n2 != null) 9 { 10 sum = (n1 == null ? 0 : (int)n1.Value) + (n2 == null ? 0 : (int)n2.Value) + carry; 11 carry = sum / 10; 12 cur.Value = sum % 10; 13 14 if(n1 != null) 15 n1 = n1.Next; 16 if(n2 != null) 17 n2 = n2.Next; 18 19 cur.Next = new LinkedListNode(); 20 cur = cur.Next; 21 } 22 23 if (carry == 1) // Don't forget the carry 24 cur.Next = new LinkedListNode(1); 25 26 return ret; 27 }
代码分析:
因为.NET提供的LinkedListNode<T>是generic的, 所以我自己写了一个LinkedListNode,里面的value用boxing Object,暂时只写了一个constractor,输入整型。
开始以为 2 -> 4 -> 3 表示243, 觉得这样麻烦了,还要反转链表,相加之后再反转。原来2 -> 4 -> 3 表示342,这样就不用反转了。
注意两点,当一个链表到头了而另外一个链表还有NODE,相加要补0。 还有注意最后一个进位。
补充一点:
我在面试的时候被问到ArrayList和List<T>有什么区别,答案是ArrayList里面的元素都是box成一个object,每次插入和读取都要boxing和unboxing,性能上自然不如泛型List.