Linked List
Add Two Numbers
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p1 = l1, p2 = l2;
ListNode preHead = new ListNode(0);
ListNode curr = preHead;
int carry = 0;
int sum = 0;
int x, y;
while (p1 != null || p2 != null) {
x = p1 == null ? 0 : p1.val;
y = p2 == null ? 0 : p2.val;
sum = x + y + carry;
curr.next = new ListNode(sum % 10);
carry = sum / 10;
if (p1 != null) p1 = p1.next;
if (p2 != null) p2 = p2.next;
curr = curr.next;
}
curr.next = carry > 0 ? new ListNode(carry) : null;
return preHead.next;
}
}Merge Two Sorted Lists
Linked List Cycle II
Last updated