data structures - Doubly Linked List in javascript -
i building linked list in javascript. dont understand 1 part.
function node(element) { this.element = element; this.next = null; this.previous = null; } function llist() { this.head = new node("head"); this.find = find; this.findlast = findlast; this.remove = remove; this.insert = insert; this.display = display; this.dispreverse = dispreverse; } function find(item) { var currnode = this.head; while(currnode.element != item) { currnode = currnode.next; } return currnode; } function display(list) { var currnode = this.head.next; while (currnode != null) { console.log(currnode.element); currnode = currnode.next; } } function insert(newelement, item) { var newnode = new node(newelement); var current = this.find(item); newnode.next = current.next; newnode.previous = current; current.next = newnode; // why dont need part? // since new node got inserted, on thoughts, // next node of current node should point new node previous 1 // current.next.previous = newnode; } function remove(item) { var currnode = this.find(item); if (currnode.next != null) { currnode.previous.next = currnode.next; currnode.next.previous = currnode.previous; currnode.next = null; currnode.previous = null; } } function findlast() { var currnode = this.head; while (currnode.next != null) { currnode = currnode.next; } return currnode; } function dispreverse() { var currnode = this.head; currnode = this.findlast(); while(currnode.previous != null) { console.log(currnode.element); currnode = currnode.previous; } } var cities = new llist(); cities.insert("conway", "head"); cities.insert("russellville", "conway"); cities.insert("carlisle", "russellville"); cities.insert("alma", "carlisle"); cities.display(); cities.remove("carlisle"); cities.display(); cities.dispreverse(); /* output should this: conway russellville carlisle alma conway russellville alma alma russellville conway */
problem insert function!
let's if have b c node already.
and want insert k after b.
currently, next , previous of b c , each.
the previous element of c b.
once put k after b,
a b k c
(1) next element of k c
(2) previous element of k b.
(3) next element of b k
(4) previous element of c k.
on code wrote in insert function, each line of codes below should process upper statements.
(1) newnode.next = current.next;
(2) newnode.previous = current;
(3) current.next = newnode;
(4) current.next.previous = newnode;
but when run whole code including (4), error has occurred.
i don understand why...
without (4) line of codes, works.
is there can me understand this?
you need step 4 before step 3:
current.next.previous = newnode current.next = newnode
as is, reference of current.next
(c) being set newnode
(k) before lookup "old" current.next
's previous
property ( current.next.previous
when points b). reference current node changed assign new value. why current.next.previous
returning newnode.previous
instead of node reference expect.
Comments
Post a Comment