所以,任务是实现链接列表和合并排序链接列表。我完全意识到,在行业中,我很可能不必实现其中的任何一种,但我认为这是练习Java的好方法。以下是我已经得到了这一点:以Java的方式合并排列LinkedList
Node类:
public class Node>
{
public E data;
public Node next;
public Node(E data)
{
this.data = data;
next = null;
}
public void printData()
{
System.out.print(data + " ");
}
}
LinkedList类:
public class LinkedList>
{
protected Node root;
protected int size = 0;
public LinkedList()
{
root = null;
}
public void addBeg(E e)
{
Node newNode = new Node(e);
newNode.next = root;
root = newNode;
size++;
}
public Node deleteBeg()
{
Node temp = root;
if(!isEmpty())
{
root = root.next;
size--;
}
return temp;
}
public void setRoot(Node newRoot)
{
root = newRoot;
}
public boolean isEmpty()
{
return root == null;
}
public Node getRoot()
{
return root;
}
public void printList()
{
Node cur = root;
while(cur!=null)
{
cur.printData();
cur=cur.next;
}
System.out.println();
}
}
MergeSorter类:
public class MergeSorter>
{
public MergeSorter()
{
}
private void split(LinkedList list, LinkedList firHalf, LinkedList secHalf)
{
//if 0 or only 1 elements in the list - it doesn't seem to work, however
if(list.getRoot() == null || list.getRoot().next == null)firHalf = list;
else{
Node slow = list.getRoot();
Node fast = list.getRoot().next;
while(fast!=null)
{
fast = fast.next;
if(fast!=null)
{
fast = fast.next;
slow = slow.next;
}
}
//If I use the following line firHalf list is empty when in the caller of this method (it's not in this method, however). Don't understand why):
//firHalf = list;
firHalf.setRoot(list.getRoot());
secHalf.setRoot(slow.next);
slow.next = null;
}
}
private LinkedList merge(LinkedList a, LinkedList b)
{
LinkedList mergedList = new LinkedList();
Node dummy = new Node(null);
Node tail = dummy;
while(true)
{
if(a.getRoot() == null){
tail.next = b.getRoot();
break;
}
else if(b.getRoot() == null){
tail.next = a.getRoot();
break;
}
else
{
if(a.getRoot().data.compareTo(b.getRoot().data) <= 0)
{
tail.next = a.getRoot();
tail = tail.next;
a.setRoot(a.getRoot().next);
}
else
{
tail.next = b.getRoot();
tail = tail.next;
b.setRoot(b.getRoot().next);
}
tail.next = null;
}
}
mergedList.setRoot(dummy.next);
return mergedList;
}
public void mergeSort(LinkedList list)
{
Node root = list.getRoot();
LinkedList left = new LinkedList();
LinkedList right = new LinkedList();
if(root == null || root.next == null) return; //base case
split(list, left, right); //split
mergeSort(left);
mergeSort(right);
list = merge(left, right); // when this mergeSort returns this list should be
// referenced by the left or right variable of the
// current mergeSort call (but it isn't!)
}
}
我对Java相当陌生(来自C背景),所以如果我的代码完全错误,我真的很抱歉。当我独立地测试MergeSorter类中的拆分和合并方法时,一切似乎都奏效(拆分由0或1个元素组成的列表不起作用,并且使我疯狂,但这不是合并排序所需的)。然而,mergeSort方法不起作用,我似乎无法找到方法。我试图自己调试它,当两个半部分合并到一个列表中,然后递归返回时,似乎会出现问题。新的合并列表应该被当前mergeSort调用的左或右变量引用,但是我只能得到最后一个元素而不是整个列表。