-
Notifications
You must be signed in to change notification settings - Fork 0
/
P27.java
54 lines (51 loc) · 1.37 KB
/
P27.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
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.io.*;
import java.util.*;
/************************************************************
*
* Following is the linked list node structure:
*
* class LinkedListNode<T> {
* T data;
* LinkedListNode<T> next;
*
* public LinkedListNode(T data) {
* this.data = data;
* }
* }
*
************************************************************/
public class P27 {
public static LinkedListNode<Integer> sortTwoLists(LinkedListNode<Integer> first, LinkedListNode<Integer> second) {
LinkedListNode res = null;
LinkedListNode head = null;
if (first == null)
return second;
if (second == null)
return first;
if (first.data > second.data) {
res = second;
second = second.next;
head = res;
} else {
res = first;
first = first.next;
head = res;
}
while (first != null && second != null) {
if (first.data > second.data) {
res.next = second;
second = second.next;
res = res.next;
} else {
res.next = first;
first = first.next;
res = res.next;
}
}
if (first != null)
res.next = first;
if (second != null)
res.next = second;
return head;
}
}