-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMergeInBetweenLinkedLists.java
41 lines (40 loc) · 1.06 KB
/
MergeInBetweenLinkedLists.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*https://leetcode.com/problems/merge-in-between-linked-lists/*/
/**
* 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 mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
ListNode aNodePrev = list1, aNode = list1, bNode = list1, temp = list1;
while (a > 0 || b > 0)
{
if (a > 0)
{
aNodePrev = aNode;
aNode = aNode.next;
--a;
}
if (b > 0)
{
bNode = bNode.next;
--b;
}
}
temp = list2;
while (temp.next != null) temp = temp.next;
if (aNode == list1)
{
temp.next = bNode.next;
return list2;
}
aNodePrev.next = list2;
temp.next = bNode.next;
return list1;
}
}