- #1
s3a
- 818
- 8
Homework Statement
Write an algorithm for reversing the order of nodes in a doubly linked list. You may assume a head and tail reference, and you may directly get and set the next field of any node, but you may not assume any add or remove methods are defined. You may assume a header or trailer rather than head or tail, if you wish.
Homework Equations
How a (Doubly) Linked List works.
The Attempt at a Solution
The teacher gave this code:
Code:
public void reverse() {
DNode cur = header.getNext();
DNode tmp;
while (cur != trailer) {
// swap the next and prev referneces
tmp = cur.getNext();
cur.setNext(cur.getPrev());
cur.setPrev(tmp);
// advance to the next node in the sequence
cur = tmp;
}
// swap the references of header.next and trailer.prev
header.setNext(trailer.getPrev());
trailer.setPrev(header.getNext());
tmp = header;
trailer = header;
header = trailer;
}
[U]However, I believe it has flaws, so here is my version, please tell me if mine is 100% correct or not[/U]:
void reverse() {
DNode cur = header.getNext();
DNode tmp;
while (cur != trailer) {
tmp = cur.getNext();
cur.setNext(cur.getPrev());
cur.setPrev(tmp);
cur = tmp;
}
tmp = trailer.getPrev();
trailer.setPrev(header.getNext());
header.setNext(tmp);
tmp = trailer;
trailer = header;
header = tmp;
}
Other question:
Also, what's the difference between a head and a header as well as a between a tail and a trailer? Or, are they the exact same thing?
Any input would be GREATLY appreciated!
Thanks in advance!
Last edited by a moderator: