ניצור פונקציית עזר המקבלת שרשרת ומספר, ומוסיפה את המספר כך שהשרשרת תמשיך להיות ממוינת בסדר עולה.
C#
public static Node<int> InsertSorted(Node<int> lst , int x){
Node<int> newNode = new Node<int>(x,null);
if(lst==null)
return newNode;
if(lst.GetValue() >=x)
{
newNode.SetNext(lst);
return newNode;
}
Node<int> p = lst;
// 8 → 70 (x=20)
while(p.HasNext()){ // p.GetNext()!=null
if(x <= p.GetNext().GetValue()){
newNode.SetNext(p.GetNext()); // 20→70
p.SetNext(newNode); // 8→20
return lst;
}
p=p.GetNext();
}
// p נימצא באיבר האחרון
// x is max
p.SetNext(newNode);
return lst;
}
פעולה עיקרית
public static Node<int> Decode(Node<int> lst){
Node<int> result = null;
while(lst!=null){
int x=0;
int counter=0;
while(lst!=null && lst.GetValue()!=-9){
x+= lst.GetValue()(Math.pow(10, counter));
counter++;
lst=lst.GetNext();
}
result = InsertSorted(result, x);
lst=lst.GetNext();
}
return result;
}