How to implement circular linked list in java?

前端 未结 2 668
情话喂你
情话喂你 2021-02-06 10:33

I read a book about \"Data structures and algorithms\" in which there is assignment which asks me to implement a circular linked list. This is a learning exercise and my code ma

相关标签:
2条回答
  • 2021-02-06 11:17

    Your delete() method doesn't handle the circularity of the list. The last element points to the first element; that also needs updating when the first element is deleted.

    In other words, you need to set last.next to point to the new first rather than the old first.

    The other issue you have is that if you delete the final element (so that it's now empty), then you also need to set last to null.

    public Link delete() {
        if (first.next == null) {
            first = null;
            last = null;
        }
        Link temp = first;
        first = first.next;
        last.next = first;
        return temp;
    } 
    
    0 讨论(0)
  • 2021-02-06 11:24

    Add last.next = first before return temp in your delete() function:

    public Link delete() {
        if(first.next == null) 
            last = null;
        Link temp = first;
        first = first.next;
        if(last != null)
            last.next = first
        return temp;
    } 
    

    Updated:

    I cannot find a scenario which satisfy first.next == null, and we should take into consideration calling delete() on an empty list.

    public Link delete() {
        Link temp = first;
        if(first == null){
            ;  // or you can throw some exception as a warning
        }
        else if(first==last){  // only one element
            first = null; // reset to initial state
            last = null;
        }
        else{
            first = first.next;
            last.next = first;
        }
        return temp;
    } 
    
    0 讨论(0)
提交回复
热议问题