java如何添加循环,如何在Java中执行循环双向链接列表添加方法

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's "first" attribute should point to the first node in the list. Its "size" attribute should store the number of elements in the list.

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.

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

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.

Here's my code:

public class DoublyLinkedList

{

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

{

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

{

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

{

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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值