/**
* 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;
}
}
/**
* 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 mergeTwoLists(ListNode list1, ListNode list2) {
ListNode p1 = list1;
ListNode p2 = list2;
ListNode p = new ListNode(0);
ListNode next = p;
while (p1 != null && p2 != null) {
if (p1.val <= p2.val) {
next.next = p1;
p1 = p1.next;
} else {
next.next = p2;
p2 = p2.next;
}
next = next.next;
}
next.next = p1 == null ? p2: p1;
return p.next;
}
}
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
// ref: https://blog.csdn.net/y492235584/article/details/88042552
ListNode slow = head;
ListNode fast = head;
while (true) {
if (fast != null && fast.next != null) {
fast = fast.next.next;
} else {
return null;
}
slow = slow.next;
if (fast == slow) break;
}
ListNode p1 = head;
ListNode p2 = slow;
while (p1 != p2) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}