-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoubleChain.java
More file actions
105 lines (91 loc) · 2.09 KB
/
Copy pathDoubleChain.java
File metadata and controls
105 lines (91 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
public class DoubleChain {
/* 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;
}
*/
private DNode head;
public DoubleChain(double val) {
/* your code here. */
head = new DNode(val);
}
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;
} // close while loop
return p;
}
/** Adds D to the front of the DoubleChain. */
public void insertFront(double d) {
/* your code here */
DNode oldHead = head;
head = new DNode(oldHead.prev, d, oldHead);
}
/** 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;
} // close while
// DNode oldBack = p;
p.next = new DNode(p, d, null);
}
/** 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;
} // close while
p = p.prev;
return p;
}
/** Returns a string representation of the DoubleChain.
* This is an extra challenge problem. */
public String toString() {
/* your code here */
// present front-to-back chain
String chain = "The double chain is: ";
String arrow = "->";
DNode p = head;
while (p.next != null) {
chain = chain + p.val + arrow;
p = p.next;
}
chain += "null;";
return chain;
}
/* DNode */
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;
}
}
public static void main(String[] args) {
DoubleChain L = new DoubleChain(0);
L.insertFront(1);
L.insertFront(2);
L.insertFront(3);
System.out.println(L.toString());
}
}