Я пытаюсь создать метод для объединения двух связанных списков для домашнего задания в моем классе программирования. Я действительно запутался здесь, метод должен иметь этот метод подписи:Как слить 2 связанных списка
public UnorderedLinkedListInt merge2(UnorderedLinkedListInt list)
, поэтому в моем методе тестирования он будет выглядеть следующим образом: list3 = list1.merge2(list2)
. Я запутался в том, как это сделать, когда метод принимает только один список, а не тот и другой. Вот мой код до сих пор
public class UnorderedLinkedListInt extends LinkedListIntClass {
//Default constructor
public UnorderedLinkedListInt() {
super();
}
public boolean search(int searchItem) {
LinkedListNode current; //variable to traverse the list
current = first;
while (current != null)
if (current.info == searchItem)
return true;
else
current = current.link;
return false;
}
public void insertFirst(int newItem) {
LinkedListNode newNode; //variable to create the new node
//create and insert newNode before first
newNode = new LinkedListNode(newItem, first);
first = newNode;
if (last == null)
last = newNode;
count++;
}
public void insertLast(int newItem) {
LinkedListNode newNode; //variable to create the new node
//create newNode
newNode = new LinkedListNode(newItem, null);
if (first == null) {
first = newNode;
last = newNode;
}
else {
last.link = newNode;
last = newNode;
}
count++;
}
public void deleteNode(int deleteItem) {
LinkedListNode current; //variable to traverse the list
LinkedListNode trailCurrent; //variable just before current
boolean found;
//Case 1; the list is empty
if (first == null)
System.err.println("Cannot delete from an empty list.");
else {
//Case 2: the node to be deleted is first
if (first.info == deleteItem) {
first = first.link;
if (first == null) //the list had only one node
last = null;
count--;
}
else { //search the list for the given info
found = false;
trailCurrent = first; //trailCurrent points to first node
current = first.link; //current points to second node
while (current != null && !found) {
if (current.info == deleteItem)
found = true;
else {
trailCurrent = current;
current = current.link;
}
}
//Case 3; if found, delete the node
if (found) {
count--;
trailCurrent.link = current.link;
if (last == current) //node to be deleted was the last node
last = trailCurrent;
}
else
System.out.println("Item to be deleted is not in the list.");
}
}
}
public void merge(UnorderedLinkedListInt list2){
UnorderedLinkedListInt list1 = this;
while (list2.first != null) {//while more data to print
list1.insertLast(list2.first.info);
list2.first = list2.first.link;
}
}
public UnorderedLinkedListInt merge2(UnorderedLinkedListInt list2){
UnorderedLinkedListInt list3 = new UnorderedLinkedListInt();
UnorderedLinkedListInt list1 = this;
while (list1.first != null) {//while more data to print
list3.insertLast(list1.first.info);
list1.first = list1.first.link;
}
while (list2.first != null) {//while more data to print
list3.insertLast(list2.first.info);
list2.first = list2.first.link;
}
return list3;
}
}
Я все еще возникают некоторые проблемы с пониманием, как именно работают связанные списки, любые предложения относительно того, как разработать этот метод будет весьма признателен.
Использовал ваш совет, и он отлично работает, спасибо! однако у меня возникла проблема с моим методом merge2, когда я запускаю его. Он добавляет list1 в list3. Я не уверен, почему он не добавляет list2? –
Ваш код изменяет списки, переданные ему. Это намеренно? – Joni
no my goal is for list2 остается неизменным и только для изменения списка1. –