高级农民
- 积分
- 1752
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-3-18
- 最后登录
- 1970-1-1
|
- public class DoubleChain {
-
- private DNode head;
-
- public DoubleChain(double val) {
- /* your code here. */
- head = new DNode(null, val, null);
- }
- public DNode getFront() {
- return head;
- }
- /** Returns the last item in the DoubleChain. */
- public DNode getBack() {
- /* your code here */
- DNode p = head;
- while (p.next != null) {
- p = p.next;
- }
- return p;
- }
-
- /** Adds D to the front of the DoubleChain. */
- public void insertFront(double d) {
- /* your code here */
- head = new DNode(null, d, head);
- }
-
- /** Adds D to the back of the DoubleChain. */
- public void insertBack(double d) {
- /* your code here */
- DNode p = head;
- while (p.next != null) {
- p = p.next;
- }
- p = new DNode(p, d, null);
- p.prev.next = p;
- }
-
- /** Removes the last item in the DoubleChain and returns it.
- * This is an extra challenge problem. */
- public DNode deleteBack() {
- /* your code here */
- DNode p = head;
- while (p.next != null) {
- p = p.next;
- }
- p.prev.next = null;
- return new DNode(p.prev, p.val, null);
- }
-
- /** Returns a string representation of the DoubleChain.
- * This is an extra challenge problem. */
- public String toString() {
- /* your code here */
- DNode p = head;
- String result = String.valueOf(p.val);
- while (p.next != null) {
- p = p.next;
- result = result + " " + String.valueOf(p.val);
- }
- return result;
- }
- public static class DNode {
- public DNode prev;
- public DNode next;
- public double val;
-
- private DNode(double val) {
- this(null, val, null);
- }
-
- private DNode(DNode prev, double val, DNode next) {
- this.prev = prev;
- this.val = val;
- this.next = next;
- }
- }
-
- }
复制代码
- import static org.junit.Assert.*;
- import org.junit.Test;
- /** Perform tests of the DoubleChain class
- */
- public class TestDoubleChain {
- /** Tests the constructor of DoubleChain */
- @Test
- public void testConstructor() {
- DoubleChain d = new DoubleChain(5);
- assertEquals(5,d.getFront().val, 1e-6);
- assertEquals(null, d.getFront().prev);
- assertEquals(null, d.getFront().next);
- }
- /** Tests some basic DoubleChain operations. */
- @Test
- public void testBasicOperations() {
- DoubleChain d = new DoubleChain(5);
- assertEquals(5, d.getFront().val, 1e-11);
- assertEquals(5, d.getBack().val, 1e-11);
- d.insertFront(2);
- d.insertFront(1);
- d.insertBack(7);
- d.insertBack(8);
- System.out.println(d.toString());
- assertEquals(1, d.getFront().val, 1e-11);
- assertEquals(8, d.getBack().val, 1e-11);
- }
- public static void main(String[] args) {
- jh61b.junit.textui.runClasses(TestDoubleChain.class);
- }
- }
复制代码 |
|