简体   繁体   English

循环链接列表节点插入Java

[英]Circular Linked List Node Insertion Java

I tried implementing the insert method for circular linked list. 我尝试为循环链表实现insert方法。 I think I had some success. 我想我取得了一些成功。

Problem: When I display the list. 问题:当我显示列表时。 The display method will loop because every next variable of the link is linked to a non-null node object. 显示方法将循环,因为链接的每个下一个变量都链接到非空节点对象。 So head will never be a null object. 所以head永远不会是null对象。 From what I recall about singly linked list, head always point to the first node in the list or the first node with data inside of it. 根据我回忆起的单链列表,头总是指向列表中的第一个节点或其中包含数据的第一个节点。

My conceptual understanding of circular linked list: From what I can understand circular linked is somewhat like a singly linked list but with a slight twist: the next variable of the tail object points to the head. 我对圆形链表的概念理解:从我的理解中,圆形链表有点像单链表,但略有不同:尾部对象的下一个变量指向头部。

I'm coding it like the diagram has presented provided by the source link. 我正在对其进行编码,就像源链接提供的图表一样。

Source: http://sourcecodemania.com/circular-linked-lists/ 资料来源: http : //sourcecodemania.com/circular-linked-lists/

public void insert(String data)
    {
        Link link = new Link(data);

        if(head == null)
        {
            head = link;
            tail= link;
        }
        else
        {
            tail.next = link;
            tail = link;
            tail.next = head;

        }
    }


public void display()
    {


        // good implementation for display #2
        while(head != null)
        {
        //  System.out.println (head.data);
            head = head.next;
        }
    }

Once you insert at least one element, you would never come across null. 一旦插入至少一个元素,就永远不会遇到null。 It will keep on going till infinity. 它会一直持续到无限远。

Also, it might not be a good idea to modify head just for displaying the list. 另外,修改head只是为了显示列表可能不是一个好主意。 Operation like display should not have any side effects. 像显示器这样的操作不应有任何副作用。

In stead, keep a member field size in your list class and update it in each insert and delete method. 相反,请在列表类中保留成员字段的大小,并在每个insert和delete方法中对其进行更新。

Now you would know how many times you should iterate the loop. 现在您将知道应该循环几次。

ListClassName current = head;    // Head is not modified.
for (int i = 0; i < this.size; i++) {
//   System.out.println (current.data);
     current = current.next;
}

Good luck. 祝好运。

You can keep a reference to the first Link object and check to make sure head is not equal to this object while looping: 您可以保留对第一个Link对象的引用,并在循环时检查以确保head不等于该对象:

 public void display()
{
    boolean first=true;
    Link firstItem=null;
    // good implementation for display #2
    while(head != null && head!= firstItem)
    {
       if(first){
           firstItem=head;
           first=false;
        }
    //  System.out.println (head.data);
        head = head.next;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM