![ישן](https://static.fresh.co.il/images/vBulletin/statusicon/post_old.gif)
27-03-2008, 08:44
|
![צלמית המשתמש של PL@yB0y](image.php?u=64479&dateline=1136229648) |
|
|
חבר מתאריך: 03.06.05
הודעות: 3,429
|
|
תיקנתי קצת אבל עדיין יש לי בעיה קטנטנה
זה בנתיים המחלקה הסופית שכתבתי (יש לי בעיה ב-add שאני אסביר אחר כך)
קוד:
import unit4.collectionsLib.List;
import unit4.collectionsLib.Node;
public class IntSet
{
private List <Integer> lst = new List <Integer> ();
public IntSet()
{
this.lst = lst;
}
public boolean exists (int x)
{
Node <Integer> pos = lst.getFirst();
while (pos != null)
{
if (pos.getInfo() == x)
return true;
pos = pos.getNext();
}
return false;
}
public void add (int x)
{
Node <Integer> pos = lst.getFirst();
if (!exists(x))
pos = lst.insert(pos, x);
}
public void delete (int x)
{
Node <Integer> pos = lst.getFirst();
while (pos != null)
{
if (pos.getInfo() == x)
pos = lst.remove(pos);
pos = pos.getNext();
}
}
public IntSet unify(IntSet set)
{
IntSet unified = new IntSet();
Node <Integer> pos1 = set.lst.getFirst();
Node <Integer> pos2 = lst.getFirst();
while (pos1 != null)
{
unified.add(pos1.getInfo());
pos1 = pos1.getNext();
}
while (pos2 != null)
{
unified.add(pos2.getInfo());
pos2 = pos2.getNext();
}
return unified;
}
public IntSet intersect (IntSet set)
{
Node <Integer> pos = lst.getFirst();
IntSet intersected = new IntSet ();
while (pos != null)
{
if (set.exists(pos.getInfo()))
intersected.add(pos.getInfo());
pos = pos.getNext();
}
return intersected;
}
public String toString()
{
return lst.toString();
}
}
עכשיו רציתי להריץ תוכנית עם המחלקה כדי לראות שהכל תקין אז הכנתי את הקטע הבא:
קוד:
import java.util.Scanner;
import unit4.collectionsLib.List;
import unit4.collectionsLib.Node;
public class check
{
public static void main(String[] args)
{
Scanner in = new Scanner (System.in);
IntSet set1 = new IntSet ();
IntSet set2 = new IntSet ();
for (int i=0; i<9; i++)
{
System.out.println("enter to first");
set1.add(in.nextInt());
}
for (int i=0; i<9; i++)
{
System.out.println("enter to second");
set2.add(in.nextInt());
}
System.out.println(set1);
System.out.println(set2);
System.out.println(set1.unify(set2));
System.out.println(set1.intersect(set2));
}
}
הכנסתי לקבוצה אחת מספרים מ 1-9, ולשנייה מ8-16 (כולל הקצוות)
הפלט שלי היה:
[1,9,8,7,6,5,4,3,2]
[8,16,15,14,13,12,11,10,9]
[8,2,3,4,5,6,7,1,9,10,11,12,13,14,15,16]
[9,8]
כלומר התוכנית פועלת כמו שצריך (נכון?!) אבל ה-add שלי לא מכניס בצורה מסודרת את האיברים לקבוצה.. יש אפשרות לסדר את זה....?
_____________________________________
|