hinzufügen und entfernen von eine einfach verknüpfte Liste

Dachte ich, ich hätte Verständnis, das in meiner vorherigen Frage zu verknüpften Listen, aber ich war schrecklich falsch, ich bin genauso verloren wie ich war, als ich anfangs gepostet.

Ich merke, dass ich technisch zwei Fragen, die aber hoffentlich immer mindestens sollte man die anderen einfach (vorausgesetzt Sie sind einfach in umgekehrter Reihenfolge).

Ich habe 3 Klassen, die bereits mir gegeben, Sie sind:

SLinkedList.java

package chapter3.linkedList;

    public class SLinkedList<V> {
        //instance variables.  Add the tail reference.
        protected Node<V> head, tail;
        protected long size;

        //methods, empty list constructor first
        public SLinkedList () {
            head = null;
            tail = null;
            size = 0;
        }  //end constructor of a SLinkedList

        //method to add nodes to the list.  Storage space for the node
        //is already allocated in the calling method
        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);    //make next of the new node refer to the head
            head = node;            //give head a new value

            //change our size
            size++;
        }  //end method addFirst

        //addAfter - add new node after current node, checking to see if we are at the tail
        public void addAfter (Node<V>currentNode, Node<V>newNode) {
            if (currentNode == tail)
                tail = newNode;
            newNode.setNext (currentNode.getNext ());
            currentNode.setNext (newNode);

            //change our size
            size++;
        }  //end method addAfter

        //addLast - add new node after the tail node.  Adapted from Code Fragment 3.15, p. 118.
        //Mike Qualls
        public void addLast (Node<V> node) {
            node.setNext (null);
            tail.setNext (node);
            tail = node;
            size++;     
        }  //end method addLast

        //methods to remove nodes from the list.  (Unfortunately, with a single linked list
        //there is no way to remove last.  Need a previous reference to do that.  (See
        //Double Linked Lists and the code below.)
        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;

            //do reference manipulation
            head = head.getNext ();
            temp.setNext(null);
            size--;

            return temp;

        }  //end method removeFirst

        //remove the node at the end of the list.  tail refers to this node, but
        //since the list is single linked, there is no way to refer to the node
        //before the tail node.  Need to traverse 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

        //method remove.  Remove a known node from the list.  No need to search or return a value.  This method
        //makes use of a 'before' reference in order to allow list manipulation.
        public void remove (Node<V> nodeToRemove) {
            //declare local variables/references
            Node<V> nodeBefore, currentNode;

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

            //starting at the beginning check for removal
            currentNode = getFirst ();
            if (currentNode == nodeToRemove)
                removeFirst ();
            currentNode = getLast ();
            if (currentNode == nodeToRemove)
                removeLast ();

            //we've already check two nodes, check the rest
            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

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

        }  //end method remove

        //the gets to return the head and/or tail nodes and size of the list
        public Node<V> getFirst () { return head; }
        public Node<V> getLast () { return tail; }  
        public long getSize () { return size; }

    }  //end class SLinkedList

Gibt es auch Node.java

package chapter3.linkedList;

public 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 class Node

und schließlich GameEntry.java

package Project_1;

public class GameEntry 
{
    protected String name;  //name of the person earning this score
    protected int score;    //the score value
    /** Constructor to create a game entry */
    public GameEntry(String name, int score) 
    {
      this.name = name;
      this.score = score;
    }
    /** Retrieves the name field */
    public String getName() 
    { 
        return name; 
    }
    /** Retrieves the score field */
    public int getScore() 
    { 
        return score; 
    }
    /** Returns a string representation of this entry */
    public String toString() 
    { 
      return name + ", " + score + "\n"; 
    }

}

SCHNITTPUNKT
Ich erstellte einen Treiber genannt Scores.java, in der es bisher allen, die ich habe ist **ich habe Hinzugefügt, was ich DENKE, ich muss für die Klassen, ich bin wahrscheinlich falsch aber:

package Project_1;

import chapter3.linkedList.*;

import java.util.*;


/** Class for storing high scores in an array in non-decreasing order. */
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> previousNode = 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;
                }               
            previousNode = currentNode;
            currentNode = currentNode.getNext();
            }
        }
        return scores;
    }

    //remove function
    public void remove(int i)
    {

    }

    //print function
    /*gameenter printing; 
printing=node.Getelement;           //pseudo code for making it work right
print(printing.getscore) 
print(print.getname) 
*/
    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("]");
    }
}

Habe ich meine test-Treiber ScoresTest.java, , ich habe ziemlich ausgefüllt:

Paket Project_1;

import chapter3.linkedList.SLinkedList;

 public class ScoresTest {
    /**
     * @param args
     */

    public static void main(String[] args) 
    {
        SLinkedList<GameEntry> highScores = new SLinkedList<GameEntry>();  //Linked List for Game Entry
        GameEntry entry;
        Scores rank = new Scores();     
        entry = new GameEntry("Flanders", 681);     
        highScores = rank.add(entry, highScores);
        entry = new GameEntry("Krusty", 324);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Otto", 438);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Bart", 875);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Homer", 12);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Lisa", 506);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Maggie", 980);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Apoo", 648);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Smithers", 150);
        highScores = rank.add(entry, highScores); 
        entry = new GameEntry("Burns", 152);
        highScores = rank.add(entry, highScores); 
        System.out.println("The Original High Scores");
        rank.print(highScores);

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

        //highScores = rank.remove(4);
        System.out.println("Scores after removing Apoo");
        rank.print(highScores);
    }
}

Ist völlig fertig, ziemlich sicher, ich habe nichts mehr hinzuzufügen.

Ich bin nicht auf der Suche für jemanden zu beantworten für mich, aber ich habe keine Ahnung, wo Sie anfangen sollen oder wie Sie die hinzufügen oder entfernen " - Funktion in keiner Weise. Dies ist ein intermediate-Kurs, das Buch tut nichts für die Erklärung von verknüpften Listen (gehen Sie voran und schauen Sie selbst, wenn Sie mir nicht glauben, wird der text aufgerufen, Datenstrukturen und Algorithmen in Java, 5. Auflage). Es wird gezeigt, wie solche, die mit einer Reihe ganz einfach...die funktioniert perfekt für eine verknüpfte Liste, aber anscheinend sind die Lehrer nicht wollen, dass wir auf diese Weise tun, so traurig es ist, ich bin jetzt völlig verloren, wie dies zu tun.

Ich habe versucht, auf der Suche nach anderen Völker, die Antworten auf die hier, und google, und bisher hat sich nichts angeklickt oder gemacht überhaupt einen Sinn, ich kann einfach nicht begreifen, wie es funktioniert, und der Lehrer seine Erklärung und das Beispiel war nur zu zeichnen-Boxen auf dem Brett, ich habe noch nie gesehen, Sortieren, hinzufügen oder entfernen-Funktion codiert für eine verknüpfte Liste...weiß ja nicht, was ich habe nicht gelehrt, oder nicht finden kann.

Jede Hilfe wird sehr geschätzt, und ich danke Ihnen im Voraus!

BEARBEITEN

Ich schaute auf den import von java.util.*; und die Befehle für verknüpfte Listen, scheinen Sie schmerzlich einfach. entfernen würde ich nur verwenden Liste.Unterliste(ich, ich).clear(); und den Wert, den ich entfernen möchte ist entfernt, super einfach, scheint es doch nur versuchen zu nutzen slinkedlist.java und node.java ich kann einfach nicht scheinen, um Ihnen zu Folgen, in irgendeiner Weise, Form oder form. Ich glaube, der Lehrer hat in der Tat schreiben, und ich habe versucht zu Fragen, für seine Hilfe, blieb 2 Stunden nach dem Unterricht zu versuchen, um zu verstehen, wie Sie von ihm, und wie Sie sehen können, es half nicht viel. Danke nochmals für die Hilfe!

BEARBEITEN

Auch ich entschuldige mich, wenn dies scheint, wie es ist vage, aber ich habe nicht einen bestimmten Punkt, wo meine Verwirrung scheint verknüpft, ich verstehe, verknüpfte Listen, wenn wir reden über die java.util.linkedList;, aber soweit mit dem was ich habe gegeben, in diesem Umstand, kann ich nicht Folgen der Logik auf alle, die mich ziemlich verloren und unsicher, wo man anfangen soll.

InformationsquelleAutor Soully | 2011-09-15

Schreibe einen Kommentar