使用链接列表进行合并排序会在Java中引发奇怪的错误

时间:2014-02-21 22:25:24

标签: java eclipse debugging linked-list

我检查了所有push,pop和peek方法,它们正常工作。我试图在Eclipse中调试此代码,并在divide()设置断点后,它直接指向'private Node next'行;在Node类中。我认为这是因为除法中的参数属于Node类。这是代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class mergeSort {

    Scanner scanner;
    Node firstNode = null;
    Node lastNode = null;
    Node currentNode = null;
    int size = 0;

    public mergeSort(String fileName) throws FileNotFoundException{
        scanner = new Scanner(new File(fileName));
        while(scanner.hasNextInt()){
            push(scanner.nextInt());
        }
    }

    public void divide(Node tempFirstNode, Node tempLastNode, int tempSize){
        if(tempFirstNode != tempLastNode){
            Node midNode = tempFirstNode;
            for(int i = 0; i < (tempSize/2-1); i++){
                midNode = tempFirstNode.next;
            }
            divide(tempFirstNode, midNode, tempSize/2);
            divide(midNode.next, tempLastNode, tempSize-tempSize/2);
            merge(tempFirstNode, tempLastNode, midNode);
        }       
    }

    public void merge(Node firstNode, Node lastNode, Node midNode){
        Node leftHead = firstNode;
        Node rightHead = midNode.next;
        Node rightTail = lastNode;

        while(leftHead != rightHead && rightHead != rightTail.next){
            if(leftHead.data <= rightHead.data){
                if(currentNode != null){
                    currentNode.next = leftHead;
                    currentNode = leftHead;
                    leftHead = leftHead.next;
                }
                else{
                    currentNode = leftHead;
                    leftHead = leftHead.next;
                }
            }
            else{
                if(currentNode != null){
                    currentNode.next = rightHead;
                    currentNode = rightHead;
                    rightHead = rightHead.next;
                }
                else{
                    currentNode = rightHead;
                    rightHead = rightHead.next;
                }
            }
        }
    }

    public void push(int newEntry) {
        Node newNode = new Node(newEntry, firstNode);
        if(lastNode == null)
            lastNode = newNode;
        firstNode = newNode;
        size++;
    }

    public int pop(){
        int top = peek();
        if(firstNode != null)
            firstNode = firstNode.next;
        size--;
        return top;
    }

    public int peek() {
        if(firstNode != null)
            return firstNode.data;
        return (Integer) null;
    }

    class Node{

        private int data;
        private Node next;

        public Node(int newData, Node nextNode){
            data = newData;
            next = nextNode;
        }
    }
}

0 个答案:

没有答案