Java - “旋转"LinkedList中的对象-LinkedList.addLast(LinkedList.removeFirst())编程的好坏? [英] Java - "Rotating" Objects in A LinkedList - Is LinkedList.addLast(LinkedList.removeFirst()) Good Or Bad Programming?

查看:50
本文介绍了Java - “旋转"LinkedList中的对象-LinkedList.addLast(LinkedList.removeFirst())编程的好坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Java应用程序中,以下两项将编译并运行,并产生所需的结果.

In my Java application both of the following will compile and run, and produce the desired result.

//"Rotate" the list items one place to the left.
myLinkedList.addLast(myLinkedList.removeFirst());

和相反方向的旋转"

//"Rotate" the list items one place to the right.
myLinkedList.addFirst(myLinkedList.removeLast());

两个轮换"都只需要一行代码,但是我想知道这是否是正确的方法?这种方法有什么陷阱吗?

Both "rotations" only require one line of code each, but I'm wondering if this is the right way to go about it? Are there any pitfalls in this approach?

是否有一种更好的,更可靠的,更不易出错的方式(与我上面的操作相同),这将需要多行代码来实现,如果是,请解释原因.

Is there a better, more robust, less error-prone way of doing the same as I have above which would require more than one line of code to achieve, and if so please explain why.

推荐答案

对我来说似乎很好.如果您有一个真正的循环缓冲区,即 full ,则可以移动开始/结束"索引,但是我认为链表方法会很好地工作.特别是它仍然是O(1).

Seems fine to me. If you had a truly circular buffer which was full you could just move the "start/end" index, but I think the linked list approach will work pretty well. In particular it's still O(1).

这篇关于Java - “旋转"LinkedList中的对象-LinkedList.addLast(LinkedList.removeFirst())编程的好坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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