删除元素后,排序的循环链表没有更新?

时间:2015-08-18 08:22:07

标签: java data-structures sortedlist circular-list

我正在实现一个排序的循环链表,首先使用已排序的元素填充列表,并为其实现插入和删除功能。但是在调用delete时,它不会更新列表。我尝试在delete方法中调试代码,但还没有成功。下面是我的程序的代码片段。

class CNode {
    public int data;
    public CNode next;

    public CNode() {
        this.data = 0;
        this.next = null;
    }

    public CNode(int data, CNode next) {
        this.data = data;
        this.next = next;
    }

    public CNode(int data) {
        this.data = data;
        this.next = null;
    }
}

和驱动程序类 -

public class SortedCLL {
    public static CNode head = new CNode();
    public static CNode last = new CNode();
    public static int NoN;

    public SortedCLL() {
        int N = 3;
        int val[] = {4, 2, 6};
        Arrays.sort(val);
        CNode first = new CNode(val[0]);
        head.next = first;
        last.next = first;
        NoN++;

        for (int i = 1; i < N; i++) {
            CNode n = new CNode(val[i]);
            last.next.next = n;
            last.next = n;
            n.next = head.next;
            NoN++;
        }

        //DELETING AN ELEMENT
        delete(2);

        //INSERTING AN ELEMENT
        insert(7);

        CNode check = head.next;
        for (int i = 0; i < NoN; i++) {
            System.out.print(check.data + " ");
            check = check.next;
        }

    }

    public static void main(String args[]) throws Exception {
        new SortedCLL();
    }

    private void insert(int element) {
        CNode n = new CNode(element);
        if(element < head.next.data) {
            n.next = head.next;
            head.next = n;
            last.next.next = n;
            NoN++;
            return;
        }
        int nodes = NoN - 1;
        CNode iter =  head;
        while(nodes-- > 0){
            if(iter.data < element && iter.next.data > element) {
                n.next = iter.next;
                iter.next = n;
                NoN++;
                return;
            }
        }
        last.next.next = n;
        last.next = n;
        n.next = head.next;
        NoN++;
        return;
    }

    private void delete(int element) {
        //System.out.println( " :  " +element);
        CNode prev = last.next;
        CNode iter =  head.next;
        int nodes = NoN;
        while(nodes-- > 0) {
            if(iter.data == element) {
                //HERE IT IS PRINTING CORRECT PREV AND NEXT NODE'S DATA.
                System.out.println( prev.data + " :  " +iter.next.data);
                prev.next = iter.next;
                NoN--;
                return;
            }
            prev = iter;
            iter = iter.next;
        }
        return;
    }

}

检查SortedCLL类中的debug语句,在delete方法中,它打印的是prev和next的正确值,仍然输出不符合预期。

expected list
  

4 6 7

program's list
  

2 4 6 7

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

您忘记了移除列表头部的边缘情况,该列表需要在删除时执行head = head.next;

此外,你并没有真正处理任何地方空列表的情况,所以要小心!