Leetcode_002_Add_Two_Numbers.java - package coding.leetcode...

  • No School
  • AA 1
  • 2

This preview shows page 1 - 2 out of 2 pages.

package coding.leetcode; /** * * 2019-02-14 다시 풀어봄 . * while loop 에서 condition || 로 연결하고 val 을 외곽에 빼놓는걸 까먹었음 . * 그리고 while loop 빠져나온 다음에 remainder 를 저장하는 것도 까먹음 . * * Sentinel 이 있어야 List 의 맨앞을 알수 있다 . * prev, cur 은 새롭게 만들어지는 list 를 잇기 위해서 쓰여진다 . * */ public class Leetcode_002_Add_Two_Numbers { public class ListNode{ public int val; public ListNode next; public ListNode(int val){ this.val = val; } } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode sentinel = new ListNode(0); ListNode prev = sentinel; ListNode cur = null; int val = 0; while(l1 != null || l2 != null){ if(l1 != null){ val += l1.val; l1 = l1.next; } if(l2 != null){ val += l2.val; l2 = l2.next; } cur = new ListNode(val%10); val /= 10; prev.next = cur; prev = cur; } // 여기서 주의해라 ! if(val > 0) prev.next = new ListNode(val); return sentinel.next; } public void test1(){ ListNode ls7 = new ListNode(7); ListNode ls1 = new ListNode(1); ListNode ls6 = new ListNode(6); ListNode ls5 = new ListNode(5);
Image of page 1
Image of page 2

You've reached the end of your free preview.

Want to read both pages?

  • Fall '19
  • Cur, 14 다시, 외곽, Sentinel 이, List 의, cur 은

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes