读书人

请代码

发布时间: 2011-12-08 21:33:54 作者: rapoo

请高手指点代码
在Eclipse下编译显示:返回类型与 Object.clone() 不兼容

及类型 Queue 中的方法 enQueue(Object)对于参数(int)不适用
interface Interface_Queue {

// only copy references
public Queue clone();

// out queue from head
// when is empty , return null
public Object deQueue();

// enter queue from tail
public void enQueue(Object o);

// get the head elem in the queue
// if empty return null
public Object getHead();

// get the tail elem in the queue
public Object getTail();

public int getLength();

public boolean isEmpty();

// print all the elem from head to tail
// return the print string
public String printAll();

// reverse all the elems from head to tail
public void reverse();

public void clean();
}

public class Queue
implements Cloneable, Interface_Queue {

class Node
implements Cloneable {
Object elem;
Node next;
Node(Object elem, Node next) {
this.elem = elem;
this.next = next;
}

// only copy references
public Node clone() {
try {
Node n = (Node)super.clone();
n.elem = this.elem;
if (this.next != null) {
n.next = (Node)this.next.clone();
}
else {
n.next = null;
}
return n;
}
catch (CloneNotSupportedException ex) {
System.err.println( "Ooop: Clone Not Supported Exception ");
ex.printStackTrace();
}
return null;
}
}

// have head node
// when the queue is empty,the head and tail point to the same head node
// enQueue from tail
// deQueue from head
private Node head = new Node(null, null);
private Node tail = head;
private int length = 0;

// only copy references
public Queue clone() {
try {
Queue n = (Queue)super.clone();
n.head = this.head.clone();
Node p = n.head;
while (p.next != null) {
p = p.next;
}
n.tail = p;


return n;
}
catch (CloneNotSupportedException ex) {
System.out.println( "Ooop: Clone Not Supported Exception ");
ex.printStackTrace();
}
return null;
}

// enter queue from tail
public void enQueue(Object o) {
tail.next = new Node(o, null);
tail = tail.next;
length++;
}

// out queue from head
// when is empty , return null
public Object deQueue() {
if (isEmpty()) {
return null;
}
Node p = head.next;
head.next = p.next;
if (tail == p) {
tail = head;
}
length--;
return p.elem;
}

// reverse all the elems from head to tail
public void reverse() {
if (length <= 1) {
return;
}
tail = head.next;
Node q = head.next, p = q.next, r = p.next;
q.next = null;
// when only two nodes
if (r == null) {
p.next = q;
head.next = p;
return;
}
// more than two nodes
while (r.next != null) {
p.next = q;
q = p;
p = r;
r = r.next;
}
p.next = q;
r.next = p;
head.next = r;
}

// get the head elem in the queue
// if empty return null
public Object getHead() {
if (isEmpty()) {
return null;
}
return head.next.elem;
}

// get the tail elem in the queue
public Object getTail() {
if (isEmpty()) {
return null;
}
return tail.elem;
}



[解决办法]
代码太长了, 谁有那么多时间看???

读书人网 >J2SE开发

热点推荐