通用单链表的实现

时间:2017-07-26 06:39:24

标签: java

网站新手。尝试实现一个通用的SinglyLinkedList,即使有节点,并且delete方法返回false,fetch返回null,当需要true时。另外,当我决定以相反的顺序删除时,它的功能很好。寻找一套新鲜的眼睛,看看我错过了什么。此结果在提前。

public class SinglyLinkedList<T> {

    private Node<T> h;  // list header

    public SinglyLinkedList() {
        h = new <T> Node();  // dummy node
        h.l = null;
        h.next = null;
    }

    public boolean insert(T newNode) {
        Node n = new Node();
        GenericNode node = (GenericNode) newNode;
        if (node == null) // out of memory
        {
            return false;
        } else {
            n.next = h.next;
            h.next = n;
            n.l = (T) node.deepCopy();
            return true;
        }
    }

    public GenericNode fetch(Object targetKey) {
        Node p = h.next;
        GenericNode node = (GenericNode) p.l; // this is where am I think there is a problem. Is this right? 
        while (p != null && !(node.compareTo(targetKey) == 0)) {
            p = p.next;
        }
        if (p != null) {
            return node.deepCopy();
        } else {
            return null;
        }
    }

    public boolean delete(Object targetKey) {
        Node q = h;
        Node p = h.next;
        GenericNode node = (GenericNode)p.l;// I think is the problem
        while (p != null && !(node.compareTo(targetKey) == 0)) {
            q = p;
            p = p.next;
        }
        if (p != null) {
            q.next = p.next;
            return true;
        } else {
            return false;
        }
    }

    public boolean update(Object targetKey, T newNode) {
        if (delete(targetKey) == false) {
            return false;
        } else if (insert(newNode) == false) {
            return false;
        }
        return true;
    }

    public void showAll() {
        Node p = h.next;
        while (p != null) //continue to traverse the list
        {
            System.out.println(p.l.toString());
            p = p.next;
        }
    }

    /**
     *
     * @param <T>
     */
    public class Node <T> {

        private T l;
        private Node <T> next;

        public <T> Node() {
        }
    }// end of inner class Node
    }
//end SinglyLinkedList outer class

1 个答案:

答案 0 :(得分:0)

问题出在这里(在fetch方法中):

    GenericNode node = (GenericNode) p.l; // this is where am I think there is a problem. Is this right? 
    while (p != null && !(node.compareTo(targetKey) == 0)) {
        p = p.next;
    }

您仅在进入循环之前协调node,并且仅在循环内更改p值,因此node在整个循环中保持其初始值。你应该使用:

    GenericNode node = null;      // define node before the loop in order to use it later
    while (p != null) {
        node = (GenericNode) p.l; // reset node value on each iteration
        if (node.compareTo(targetKey) == 0) {
            break;
        }
        p = p.next;
    }

由于您在delete中使用了相同的代码,因此同样的修补程序将适用...