Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> помогите! 
:(
    Опции темы
insense
Дата 31.8.2007, 22:17 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 7
Регистрация: 12.7.2007

Репутация: нет
Всего: нет



помогите сделать из этого(бинарное дерево) линейный список
Код

class Node {
    public Node left;
    public Node right;
    public Flat value;

    Node(Flat value) {
        this.value = value;
    }

    Node(Node node) {
        this.left = node.left;
        this.right = node.right;
        this.value = node.value;
    }
}

public class BST {
    Node root;

    int size = 0;

    int i;

    public void add(Flat f) {
        if (this.root == null && f != null) {
            this.root = new Node(f);
            this.size++;
        } else if (f != null) {
            this.root = insert(this.root, f);
        }
    }

    private Node insert(Node node, Flat value) {
        Node result = new Node(node);
        int compare = result.value.compareTo(value);

        if (compare == 0) {
            return result;
        }

        if (compare > 0) {
            if (result.left != null) {
                result.left = insert(result.left, value);
            } else {
                result.left = new Node(value);
                this.size++;
            }
        }

        else if (compare < 0) {
            if (result.right != null) {
                result.right = insert(result.right, value);
            } else {
                result.right = new Node(value);
                this.size++;
            }
        }

        return result;
    }

    public Flat get(Flat key) {
        if (this.root == null)
            return null;
        else
            return find(this.root, key);
    }

    private Flat find(Node node, Flat searchValue) {
        int compareResult;
        Flat result = null;
        if ((compareResult = node.value.compareTo(searchValue)) == 0) {
            return node.value;
        } else if (compareResult > 0) {
            if (node.left != null)
                return find(node.left, searchValue);
        } else {
            if (node.right != null)
                return find(node.right, searchValue);
        }
        return result;
    }

    public static void searchFlat(int r, int f, int s, String addr, Node a) {
        if (a != null) {
            searchFlat(r, f, s, addr, a.left);
            if (a.value.floor == f && a.value.rooms == r) {
                if (a.value.square >= s - s * 0.1
                    && a.value.square <= s + s * 0.1) {
                    Flat.printFlat(a.value);
                }
            }
            searchFlat(r, f, s, addr, a.right);
        }
    }

    public static void inorderWalk(Node a) {
        if (a != null) {
            inorderWalk(a.left);
            Flat.printFlat(a.value);
            inorderWalk(a.right);
        }
    }

}


вот что ещо нужно, чтобы это работало
Код

import java.io.*;
import java.util.Random;

public class Main {
    public static BST bst = new BST();

    @SuppressWarnings("deprecation")
    public static void readFile(String filename) {
        File file = new File(filename);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;
        String[] result = null;
        try {
            fis = new FileInputStream(file);
            // Here BufferedInputStream is added for fast reading.
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);
            // dis.available() returns 0 if the file does not have more lines.
            while (dis.available() != 0) {
                // this statement reads the line from the file and print it to
                // the console.
                // System.out.println(dis.readLine());
                String line = dis.readLine();
                result = line.split("; ");
                bst.add(new Flat(Integer.valueOf(result[1]), Integer
                        .valueOf(result[2]), Integer.valueOf(result[3]),
                        result[0]));
            }

            // dispose all the resources after using them.
            fis.close();
            bis.close();
            dis.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeToFile(String filename, String pishem) {
        try {
            // Create a file descriptor
            File fp = new File(filename);
            // Open in append mode if you wont add line at the end of file
            FileWriter fw = new FileWriter(fp, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(pishem);
            bw.flush();
            bw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {
        readFile("flats");
        Gui g = new Gui();
    }

}


Код

public class Flat implements Comparable<Flat>{
    public int rooms, floor;
    int square;
    public String address;
    
    public Flat(int r, int f, int s, String a) {
        this.address = a;
        this.floor = f;
        this.rooms = r;
        this.square = s;
    }
    public int compareTo(Flat o) {
        if (this.square < o.square){
            return -1;
        } else if (this.square == o.square) { 
            return 0;
        } else if (this.square > o.square){
            return 1;
        }
        return 0;
    }
    public static void printFlat(Flat f) {
        String prev = Gui.searchResults.getText();
        Gui.searchResults.setText(prev + "\n" + f.address + ", " + f.floor + " floor, " + f.rooms + " rooms, square of " + f.square);
    }
    

}



Код

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class Gui {
    private static final long serialVersionUID = 1L; // dunno WTF it is, lol

    static JTextArea searchResults = new JTextArea("Started successfully");

    static JTextField rooms = new JTextField("rooms", 5);

    static JTextField floor = new JTextField("floor", 5);

    static JTextField square = new JTextField("square", 5);

    static JTextField addr = new JTextField("Address", 10);

    Action action = new AbstractAction("Find") {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent evt) {
            searchResults.setText("Searching...");
            int r = Integer.valueOf(rooms.getText());
            int f = Integer.valueOf(floor.getText());
            int s = Integer.valueOf(square.getText());
            String address = addr.getText();
            if (r < 1) {
                searchResults.setText("Error: wrong # of rooms");
            } else if (f < 1) {
                searchResults.setText("Error: wrong floor #");
            } else if (s < 1) {
                searchResults.setText("Error: wrong square");
            } else {
                BST.searchFlat(r, f, s, address, Main.bst.root);
                if (searchResults.getText().equals("Searching...")) {
                    Main.writeToFile("flats", address + "; " + r + "; " + f
                            + "; " + s + "\n");
                    searchResults.setText("Searching...\nNo suitable results;\nyour query has been added to the database.");
                }
            }
        }
    };

    public Gui() {
        JFrame top = new JFrame("Flats exchange");
        final JFrame findDialog = new JFrame("Search query");
        findDialog.setVisible(false);
        top.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        Container topContentPane = top.getContentPane();
        Container sContentPane = findDialog.getContentPane();
        sContentPane.setLayout(new FlowLayout());

        // Button

        JButton button = new JButton(action);

        // Menu
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        menuBar.add(menu);
        JMenuItem exit = new JMenuItem("Exit");
        exit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        top.setJMenuBar(menuBar);
        JMenuItem find = new JMenuItem("Find flat");
        find.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                findDialog.setVisible(true);
            }
        });
        JMenuItem display = new JMenuItem("Display database");
        display.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                searchResults.setText("Current database entries:");
                Main.readFile("flats");
                BST.inorderWalk(Main.bst.root);
            }
        });
        menu.add(find);
        menu.add(display);
        menu.add(exit);

        // Textboxez

        rooms.setVisible(true);
        floor.setVisible(true);
        square.setVisible(true);
        rooms.setEditable(true);
        floor.setEditable(true);
        square.setEditable(true);
        topContentPane.add(searchResults);
        sContentPane.add(rooms);
        sContentPane.add(floor);
        sContentPane.add(square);
        sContentPane.add(addr);
        sContentPane.add(button);
        searchResults.setEditable(false);
        searchResults.setVisible(true);
        // Launch!
        top.setSize(300, 400);
        findDialog.setSize(220, 100);
        top.setVisible(true);
    }
}




заранее спасибо!

PM MAIL   Вверх
y3u
Дата 1.9.2007, 12:41 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 440
Регистрация: 9.9.2006
Где: Москва

Репутация: 5
Всего: 13



ИМХО, тупо удалить связь public Node left; из Node и все smile 
Ну и хранить ссылку на Root.

Это сообщение отредактировал(а) y3u - 1.9.2007, 12:42


--------------------
В нашей стране настаивать на кореньях, черной смородине, лимонных корках - гораздо эффективнее, чем на правах
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0435 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.