package heap;
public class SortedListInt {
//Fields
SLNode first;
//Methods
public SortedListInt(){
first = null;
}//Constructor
public boolean empty(){
return (first == null);
}
public void insert(int data){
SLNode curr, foll;
if ((first == null) || (data <= first.data)) // Insertion at the beginning
first = new SLNode(data,first);
else {
curr = first; foll = first.next;
while ((foll != null) && (foll.data < data)){
curr = foll; foll = foll.next;
}
curr.next = new SLNode(data,foll);
}
}//insert
public void insert(int[] dataArr){
for (int i = 0;i < dataArr.length;i++)
insert(dataArr[i]);
}
public void merge(SortedListInt l){
SLNode p1,p2,prev;
//if (first == null) first = l.first;
//else if (!l.empty()) { // this and l are not empty
p1 = first; p2 = l.first;
if (p1.data <= p2.data) p1 = p1.next;
else { first = p2; p2 = p2.next; }
prev = first;
while ((p1 != null) && (p2 != null)){
if (p1.data <= p2.data){
prev.next = p1;
p1 = p1.next;
}
else {
prev.next = p2;
p2 = p2.next;
}
prev = prev.next;
}
if (p1 == null) prev.next = p2;
else prev.next = p1;
//}
}
public String toString(){
String out = "[";
SLNode aux = first;
while (aux != null){
out += aux.data;
aux = aux.next;
if (aux != null)
out += ",";
}//while
out += "]";
return out;
}
public boolean equals(Object obj){
if (obj instanceof SortedListInt){
SortedListInt list;
list= (SortedListInt) obj;
if (list.first==null) return this.first==null;
if (this.first==null) return list.first==null;
return this.first.equals(list.first);
}
return false;
}
public static void main(String[] args) {
SortedListInt l1 = new SortedListInt();
int[] d1 = {3,3};
l1.insert(d1);
System.out.println(l1);
SortedListInt l2 = new SortedListInt();
int[] d2 = {2,4};
l2.insert(d2);
System.out.println(l2);
l1.merge(l2);
System.out.println(l1);
}
}
|