如何在Java中执行循环双向链接列表添加方法 [英] How to do a cyclic doubly link list add method in java

查看:103
本文介绍了如何在Java中执行循环双向链接列表添加方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在循环DoublyLinkedList类以及Node内部类中实现add(E)方法。

I am implementing the add(E) method in the cyclic DoublyLinkedList class as well as the Node inner class.

节点应作为私有内部类实现。

Node should be implemented as a private inner class.

DoublyLinkedList的 first属性应指向第一个列表中的节点。它的大小属性应该存储列表中元素的数量。

DoublyLinkedList's "first" attribute should point to the first node in the list. Its "size" attribute should store the number of elements in the list.

我在自己的add方法上苦苦挣扎,因为感觉好像没有什么不对,而且我没有我还知道我可以添加此代码来解决此问题。

I am struggling on my add method, because it feels like nothing is wrong and I don't know what else I can add this this code that can fix it.

因此简要介绍了add方法应该做什么。

Therefore a brief introduction on what the add method should do.

add(E)方法应将value参数添加到列表的末尾。确保解决列表为空和/或添加的元素为列表中第一个元素的情况。

The add(E) method should add the value parameter to the end of the list. Be sure to address the case in which the list is empty and/or the added element is the first in the list.

这是我的代码:

public class DoublyLinkedList<E>
{
private Node first;
private int size;

@SuppressWarnings("unchecked")
public void add(E value)
{
    if(first == null)
    {
        first = new Node(value, null, null);
        first.next = first;
        first.prev = first;
    }
    else
    {
        first = new Node(value, first.next, first.prev);
        first.next = first.prev;
        first = first.next;
        first.prev = first;
    }
    size++;
}
private class Node<E>
{
    private E data;
    private Node next;
    private Node prev;

    public Node(E data, Node next, Node prev)
    {
        this.data = data;
        this.next = next;
        this.prev = prev;
    }
  }
 }


推荐答案

以最小的更改固定代码(只是添加情况中的其他情况):

Code fixed with minimal change (just the else case in add):

class DoublyLinkedList<E>
{
    private Node first;
    private int size;

    public void add(E value)
    {
        if(first == null)
        {
            first = new Node(value, null, null);
            first.next = first;
            first.prev = first;
        }
        else
        {
            first.prev.next = new Node(value, first, first.prev);
            first.prev = first.prev.next;
        }
        size++;
    }

    private class Node<E>
    {
        private E data;
        private Node next;
        private Node prev;

        public Node(E data, Node next, Node prev)
        {
            this.data = data;
            this.next = next;
            this.prev = prev;
        }
    }
}

这篇关于如何在Java中执行循环双向链接列表添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆