Linked List
Add Two Numbers
Link: https://leetcode.com/problems/add-two-numbers/
Code:
/**
* 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;
}
}add one more node if the last carry is not zero;
/operation can cast to ainttype if the variable to be assigned is ainttype.%is the remainder of the division.
Merge Two Sorted Lists
Link: https://leetcode.com/problems/merge-two-sorted-lists/
Code:
next = next.next;is crucial to append the linked list;It is not needed to append the remaining node (in list1 or list2) one by one;
next.next = p1 == null ? p2 : p1is another way to writeif (p1 == null) { next.next = p2; } else { next.next = p1; }
Linked List Cycle II
Link: https://leetcode.com/problems/linked-list-cycle-ii/
Code:
Last updated