У меня есть проект, над которым я работаю, для которого требуется реализация кругового сравниваемого списка без использования API. Я сделал большую часть кода, но по некоторым причинам я не могу получить вывод, который я ищу. Я любезно прошу всех, кто может помочь мне решить проблему. Одна из конкретных проблем заключается в том, что я не могу поместить указатель в начало итерации из ключа, найденного в методе find. например если элементы массива составляют 10, 9, 8, 5,6. если я передам 8 в качестве аргумента методу поиска, если он найден, он должен отображаться как 8,5,6,10, 9 и т. д., в противном случае оставить элементы такими, какие они есть.Как реализовать круговой связанный список в Java?
Ниже приведен код, который у меня есть, и ПОЖАЛУЙСТА, посмотрите, как он выходит прямо под ним, я думаю, это поможет вам разобраться в том, что я ищу специально. Обратите особое внимание на мой метод вставки, поиска, шага. ! Спасибо заранее `
//LinkFirstLast Classs
class LinkFirstLast {
public long theData;
public LinkFirstLast next;
public LinkFirstLast last;
public LinkFirstLast previous;
public LinkFirstLast() {
}
public LinkFirstLast(int data) {
theData =data;
}
public void displayLink(){
System.out.print(theData+ " ");
}
}
// Circular linklist class//////////////////
class CircList {
private LinkFirstLast first, last;
int nItems;
//Constructor
public CircList(){
last = null;
}
//Creates a node and inserts new data
public void insert(int data) {
LinkFirstLast newLink = new LinkFirstLast(data);
if(isEmpty()){
last = newLink;
// first = newLink;
}
else{
first.previous = newLink;
}
newLink.next = first;
first = newLink;
//last.next = first;
// first.previous = last;
nItems++;
}
public void displayList() {
LinkFirstLast current = first;
while(current != null){
current.displayLink();
current =current.next;
}
System.out.println("");
}
public LinkFirstLast find(int key) {
LinkFirstLast current = first;
while(current != null && current.theData != key){
if(current.theData == key){
first = current;
first = current.next;
last.next = first;
}
else{
current = current.next;
}
}
/*
first.previous = newLink;
newLink.next = first;
first = newLink;
LinkFirstLast current = first;
while(current != null && current.theData != key )
{
current = current.next;
}
*/
return current;
}
public LinkFirstLast delete() {
LinkFirstLast current;
current = first;
while(first.next == null){
last = null;
}
first = first.next;
return current;
}
public int getSize() {
return nItems;
}
public void step() {
System.out.print("List: ");
if(first != null && first.next !=null){
first.next= first.next;
}
}
//Checks if linkedlist has no item
public boolean isEmpty() {
return (nItems==0);
}
public LinkFirstLast delete(int key) {
LinkFirstLast current = first;
LinkFirstLast previous = first;
while(current.theData != key)
{
if(current.next == null)
return null;
else
{
previous = current;
current = current.next;
}
}
if(current == first)
first = first.next;
else
previous.next = current.next;
nItems--;
return current;
}
// -------------------------------------------------------------
}
// main
class Pro {
public static void main(String[] args)
{
LinkFirstLast f, d;
CircList theList = new CircList(); // make list
theList.insert(10); // insert items
theList.insert(20);
theList.insert(30);
theList.insert(40);
theList.insert(50);
theList.insert(60);
theList.insert(70);
theList.displayList();
f = theList.find(30);
if(f != null){
System.out.println("Found link with key " + f.theData);
}
else{
System.out.println("Can't find link with key 30");
}
theList.displayList(); // display list
System.out.println("Inserting link with key 80");
theList.insert(80);
theList.displayList(); // display list
d = theList.delete(60); // delete item
if(d != null)
System.out.println("Deleted link with key " + d.theData);
else
System.out.println("Can't delete link with key 60");
theList.displayList(); // display list
f = theList.find(99); // find item
if(f != null){
System.out.println("Found link with key " + f.theData);}
else
System.out.println("Can't find link with key 99");
theList.displayList(); // display list
d = theList.delete(13); // delete item
if(d != null)
System.out.println("Deleted link with key " + d.theData);
else
System.out.println("Can't delete link with key 13");
theList.displayList(); // display list
System.out.println("Stepping through list");
for(int j=0; j<theList.getSize(); j++)
{
theList.step();
theList.displayList();
}
System.out.println("Will delete and step one by one");
while(theList.isEmpty() == false)
{
theList.delete();
theList.step();
theList.displayList();
}
} // end main()
} // end class CircApp
Выход:
List: 70 60 50 40 30 20 10
Found link with key 30
List: 30 20 10 70 60 50 40
Inserting link with key 80
List: 80 30 20 10 70 60 50 40
Deleted link with key 60
List: 50 40 80 30 20 10 70
Can't find link with key 99
List: 50 40 80 30 20 10 70
Can't delete link with key 13
List: 50 40 80 30 20 10 70
Stepping through list
List: 40 80 30 20 10 70 50
List: 80 30 20 10 70 50 40
List: 30 20 10 70 50 40 80
List: 20 10 70 50 40 80 30
List: 10 70 50 40 80 30 20
List: 70 50 40 80 30 20 10
List: 50 40 80 30 20 10 70
Will delete and step one by one
List: 80 30 20 10 70 40
List: 20 10 70 40 30
List: 70 40 30 10
List: 30 10 40
List: 40 10
List: 10
List:
Вы должны найти 'key' узел и присвоить ему голову node.If ключ не найден, просто оставьте голову там, где она есть. Надеюсь, это сработает для вас. –
Я ценю ваше внимание. Я думаю, что я на самом деле это сделал, но он просто поместил ключ в голову, а не просто вращал все. Также мой шаг() не дает мне права Out, а также просто копирует элементы на каждой итерации, а не просто вращает их против часовой стрелки. – Ali
Ничего не нужно поворачивать, вам нужно только сдвинуть голову в положение ключа. Отдых будет в конце концов! –