0
我是Java新手(約4個月)。我剛剛拿到了Robert Lafore的「Data Structures & Java算法」第二版的副本,我正在閱讀章節並試圖解決後面的問題。因爲我沒有參加正式課程,所以我需要一些評分方式來教我如何改進我的工作。比堆棧中的天才更好的地方。鏈接列表Java Java中的FIFO排隊更正
我目前在第5章鏈接列表上。
這是問題5.1 實現基於有序鏈表上的優先級隊列。優先級隊列上的刪除操作 應刪除具有最小密鑰的項目。
容器類
public class LinkLL {
public static LinkLL leftConnector; //left side of node
public static String fName; //item in actual node
public static LinkLL rightConnector; //Right side of node
public LinkLL(String key)
{
fName = key;
//A new LinkLL linked list has been Instantiated,
//although it is empty.
rightConnector = null;
leftConnector = null;
}
public void showName()
{
System.out.print(fName + " " + "There are " + SortedLL.nElems + "in the list at this moment.");
}
}
在這裏我們有方法,如插入,delete..etc。我覺得我在「插入」和刪除方面做得很好?但我的「排序」和「展示」正在爲我賺錢奔走。例如,我想顯示每個輸入的字符串,但是我擁有它的方式,只有第一個顯示。
「抽象」
public class SortedLL {
static LinkLL currentNode;
static LinkLL firstNode;
static final LinkLL lastNode = null;
static LinkLL prequelNode;
static LinkLL sequelNode;
static float nElems;
static LinkLL l;
public static void insert(String key)
{
if (nElems == 0) //could have also been if(nElems == 0)
{
l = new LinkLL(key); //if nothing exists, create one
l.rightConnector = sequelNode;//the right connector is equal to the sequelNode
sequelNode = lastNode; // Sequel Node is equal to lastNode which is 'null'.
prequelNode = sequelNode;
firstNode.leftConnector = lastNode;
}
else if(!(nElems == 0))
{
LinkLL NewEndNode;
NewEndNode = lastNode;
l.rightConnector = NewEndNode;
l.leftConnector = prequelNode.rightConnector;
}
//when such occurs, nodes must be re-connected
nElems++;
}
public void remove()
{
if(nElems == 0) System.out.println("There are no items to remove.");
//if(!find(key)) System.out.println(key +" could not be located, " + "and thus cannot be removed.");
//while (find(key) ) //while the key can be found
{
//currentNode = key;
prequelNode.rightConnector = sequelNode.leftConnector;
nElems--;
}
//when such occurs, nodes should be reconnected
}
public boolean find(LinkLL key)
{
if (isEmpty() == true)
{
System.out.println("The List is Empty");
}
else
{
for(int i = 0; i<nElems+1; i++)
{
if (i == nElems+1)
//added '+1' to make sure that the item to be searched for is not at the bottom(list scanned throughly)
System.out.println("The key " + key + "has NOT been found!");
else
System.out.println("The key " + key + "has been found!");
}
}
return true;
}
public void sort()
{
}
public boolean isEmpty()
{
if (firstNode != null) return false;
else return false;
}
public void displayNode()
{
LinkLL first = null;
LinkLL current = first ;
while (current != null)
{
l.showName();
current = current.rightConnector;
}
}
}
的Main()
public class sortedLLApp {
public static void main(String []args)
{
SortedLL s = new SortedLL();
s.isEmpty();
s.insert("Jack");
s.insert("Jill");
s.insert("John");
s.insert("Jenn");
s.insert("James");
s.displayNode();
}
}