Java链接列表

时间:2014-09-29 23:56:33

标签: java

我似乎无法弄清楚为什么它会打印重复的条目而不按列出的顺序打印。有什么想法吗。这是我的驱动程序代码。

ScoresTest

public class ScoresTest 
{
    public static void main(String[] args) 
    {       
        // create 
        SLinkedList<GameEntry> highScores = new SLinkedList<GameEntry>();  
        GameEntry entry;

        // create entries.
        Scores rank = new Scores();     
        entry = new GameEntry("Rick", 234);     
        highScores = rank.add(entry, highScores);
        entry = new GameEntry("Steve", 121);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Jeremy", 438);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Mike", 925);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Craig", 465);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Juan", 777);
        highScores = rank.add(entry,highScores); 

        System.out.println("The Original High Scores");
        rank.print(highScores);

        entry = new GameEntry("Tyler", 895);
        highScores = rank.add(entry, highScores);
        System.out.println("Scores after adding Tyler");
        rank.print(highScores);
    }
}

GameEntry

public class GameEntry  
{
    private String name;        // name of the person earning this score
    private int score;          // the score value

    // Constructor
    public GameEntry(String n, int s) 
    {
        name = n;
        score = s;
    }

    // Get methods.

    public String getName() { return name; }
    public int getScore() { return score; }

    // Return string representation.
    public String toString() 
    {
        return "(" + name + ", " + score + ")";
    } 
}// end class.

得分

import Project1.SLinkedList.Node;

public class Scores 
{
    //add function
    public SLinkedList<GameEntry> add(GameEntry rank, SLinkedList<GameEntry> scores)
    {
        Node<GameEntry> currentNode = scores.getFirst();
        Node<GameEntry> nextNode = null;
        Node<GameEntry> newNode = new Node<GameEntry>();
        newNode.setElement(rank);

        if(scores.getSize() == 0)
        {
            scores.addFirst(newNode);
        }
        else
        {
            while(currentNode != null)
            {               
                nextNode = currentNode.getNext();
                if(nextNode == null)
                {
                    scores.addLast(newNode);
                }
                else
                {
                    scores.addAfter(currentNode, newNode);
                    break;
                }               
                currentNode = currentNode.getNext();
            }
        }
        return scores;
    }

    // Print Format.

    public void print(SLinkedList<GameEntry> scores)
    {
        Node<GameEntry> currentNode = scores.getFirst();        
        GameEntry currentEntry = currentNode.getElement();      
        System.out.printf("[");
        for(int i = 0; i < scores.getSize(); i++)
        {
            System.out.printf(", %s", currentEntry.toString());
            currentNode = currentNode.getNext();
            currentEntry = currentNode.getElement();
        }
        System.out.println("]");
    }   
}

SLinkedList

public class SLinkedList<V> implements Cloneable 
{
    public static class Node<V> 
    {
        // instance variables
        private V element;
        private Node<V> next;

        // methods, constructor first
        public Node () 
        {
            this (null, null);      // call the constructor with two args
        }  // end no argument constructor
        public Node (V element, Node<V> next) 
        {
            this.element = element;
            this.next = next;
        }  // end constructor with arguments

        // set/get methods
        public V getElement () 
        { 
            return element; 
        }
        public Node<V> getNext () 
        { 
            return next; 
        }
        public void setElement (V element) 
        { 
            this.element = element; 
        }
        public void setNext (Node<V> next) 
        { 
            this.next = next; 
        }

    } // End of nested node class


    // instance variables.  
    protected Node<V> head, tail;
    protected long size;

    // Create empty constructor
    public SLinkedList () {
        head = null;
        tail = null;
        size = 0;
    } // end constructor 

    // Add Fist method to add node to list. 
    public void addFirst (Node<V> node) {
        // set the tail only if this is the very first node
        if (tail == null)
            tail = node;
        node.setNext (head);    //refer to head
        head = node;            

        // adjust size.
        size++;
    }  // end addFirst method.

    // Add new node after current node. Checks to see if at tail also.
    public void addAfter (Node<V>currentNode, Node<V>newNode) {
        if (currentNode == tail)
            tail = newNode;
        newNode.setNext (currentNode.getNext ());
        currentNode.setNext (newNode);

        // adjust size.
        size++;
    }  // end addAfter method.


    // Add new node after the tail. 

    public void addLast (Node<V> node) {
        node.setNext (null);
        tail.setNext (node);
        tail = node;
        size++;     
    }  // end addLast method



    // Removes first node.  
    public Node<V> removeFirst () {
        if (head == null)
            System.err.println("Error:  Attempt to remove from an empty list");

        // save the one to return.
        Node<V> temp = head;

        head = head.getNext ();
        temp.setNext(null);
        size--;

        return temp;

    }  // end method removeFirst

    // remove the node at the end of the list.  
    public Node<V> removeLast () {
        // // declare local variables/objects
        Node<V> nodeBefore;
        Node<V> nodeToRemove;

        // make sure we have something to remove
        if (size == 0)
            System.err.println("Error:  Attempt to remove fron an empty list");

        // traverse through the list, getting a reference to the node before
        // the trailer.  Since there is no previous reference.
        nodeBefore = getFirst ();

        // potential error  ??  See an analysis and drawing that indicates the number of iterations
        // 9/21/10.  size - 2 to account for the head and tail nodes.  We want to refer to the one            before the
        // tail.
        for (int count = 0; count < size - 2; count++)
            nodeBefore = nodeBefore.getNext ();

        // save the last node
        nodeToRemove = tail;

        // now, do the pointer manipulation
        nodeBefore.setNext (null);
        tail = nodeBefore;
        size--;

        return nodeToRemove;

    }  // end method removeLast

    // Remove known node from list. Traverses through the list.
    public void remove (Node<V> nodeToRemove) {

        // declare local variables/references
        Node<V> nodeBefore, currentNode;

        // is there something to remove.
        if (size == 0)
            System.err.println("Error:  Attempt to remove fron an empty list");

        // Start at beginning of list.
        currentNode = getFirst ();
        if (currentNode == nodeToRemove)
            removeFirst ();
        currentNode = getLast ();
        if (currentNode == nodeToRemove)
            removeLast ();

        // Check last two nodes.
        if (size - 2 > 0) {
            nodeBefore = getFirst ();
            currentNode = getFirst ().getNext ();
            for (int count = 0; count < size - 2; count++) {
                if (currentNode == nodeToRemove) {

                    // remove current node
                    nodeBefore.setNext (currentNode.getNext ());
                    size--;
                    break;
                }  // end if node found

                //  references
                nodeBefore = currentNode;
                currentNode = currentNode.getNext ();
            }  // end loop to process elements
        }  // end if size - 2 > 0

    }  // end method remove

    // Get methods 
    public Node<V> getFirst () { return head; }
    public Node<V> getLast () { return tail; }  
    public long getSize () { return size; }
}

这是我的输出。

  

The Original High Scores [,(Rick,234),(Juan,777),(Craig,465),   (Mike,925),(Jeremy,438),(Steve,121),(Steve,121),(Steve,121)]

     

加入Tyler后得分[,(Rick,234),(Tyler,895),(Juan,777),   (克雷格,465),(迈克,925),(杰里米,438),(史蒂夫,121),(史蒂夫,121),   (史蒂夫,121)]

1 个答案:

答案 0 :(得分:0)

while循环while(currentNode != null)只执行一次,因为如果当前项为非null,则内部条件将中断。所以它基本上总是在第一个项目之后添加新项目。

方法add中的逻辑非常错误。