-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path27_MergeTwoSortedLinkedLists.java
43 lines (36 loc) · 1.19 KB
/
27_MergeTwoSortedLinkedLists.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
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 Solution {
public static LinkedListNode<Integer> sortTwoLists(LinkedListNode<Integer> first, LinkedListNode<Integer> second) {
if(first==null) return second;
if(second==null) return first;
if(second.data<first.data){
LinkedListNode<Integer> temp=first;
first=second;
second=temp;
}
LinkedListNode<Integer> res=first;
while(first!=null && second!=null){
LinkedListNode<Integer> tmp=null;
while(first!=null && first.data<=second.data){
tmp=first;
first=first.next;
}
tmp.next=second;
LinkedListNode<Integer> temp=first;
first=second;
second=temp;
}
return res;
}
}