如何使用下面的实现在 Java 中使用 Linked List 实现“MergeSort”?这是我对链表的实现:
public class LinkedList {
Node tail;
public LinkedList() {
tail = null;
}
public LinkedList(Object value) {
tail = new Node(value);
tail.setNext(tail);
}
public void purge() {
tail = null;
}
public Object getFirst() {
Node rigby = tail.getNext();
return rigby.getValue();
}
public Object getLast() {
return tail.getValue();
}
public boolean isEmpty() {
return (tail == null);
}
public void assign(LinkedList list) {
if (list.isEmpty())
tail = null;
else {
this.append(list.tail.getNext().getValue());
Node tmp = list.tail.getNext();
while (tmp != list.tail) {
tmp = tmp.getNext();
this.append(tmp.getValue());
}
}
}
public void append(Object value) {
if (this.isEmpty()) {
tail = new Node(value);
tail.setNext(tail);
} else {
Node tmp = new Node(value);
tmp.setNext(tail.getNext());
tail.setNext(tmp);
tail = tmp;
}
}
public void prepend(Object value) {
if (this.isEmpty()) {
tail = new Node(value);
tail.setNext(tail);
} else {
Node tmp = new Node(value);
tmp.setNext(tail.getNext());
tail.setNext(tmp);
}
}
public boolean equals(LinkedList list) {
if (this != list) {
// temp variables
Node mordecai = tail.getNext();
Node rigby = list.tail.getNext();
// previouses
Node prev = tail;
Node prev2 = list.tail;
while (true) {
if (mordecai.getValue().getClass().getName() == "Node") {
if (!mordecai.getValue().equals(rigby.getValue()))
return false;
} else {
if (!mordecai.getValue().toString().equals(rigby.getValue().toString()))
return false;
}
prev = mordecai;
mordecai = mordecai.getNext();
prev2 = rigby;
rigby = rigby.getNext();
if ((prev == tail) && (prev2 == list.tail))
return true;
if ((prev == tail) || (prev2 == list.tail))
return false;
}
}
return true;
}
public void extract(Object value) {
if (!this.isEmpty()) {
Node tmp = tail.getNext();
Node prev = tail;
while (true) {
if (tmp.getValue().equals(value)) {
prev.setNext(tmp.getNext());
break;
}
prev = tmp;
tmp = tmp.getNext();
if (prev == tail)
break;
}
}
}
public String toString() {
if (this.isEmpty()) {
return null;
} else {
String str = "";
Node tmp = tail.getNext();
str += tmp.getValue().toString();
while (tmp != tail) {
str += " -> ";
tmp = tmp.getNext();
str += tmp.getValue().toString();
}
return str;
}
}
class Node {
Object data;
Node next;
public Node(Object value) {
data = value;
}
public Node(Object value, Node pointer) {
data = value;
next = pointer;
}
public Object getValue() {
return data;
}
public void setValue(Object value) {
data = value;
}
public Node getNext() {
return next;
}
public void setNext(Node pointer) {
next = pointer;
}
public boolean equals(Node var) {
if (next.equals(var.next)) {
if (data.getClass().getName() == "Node") {
if (data.equals(var.data))
return true;
} else {
if (data.toString().equals(var.data.toString()))
return false;
}
}
return false;
}
}
}
我不能正面或反面,分析让我偏头痛。我需要这方面的帮助。我已经搜索过,我只找到了一个 Array 实现。