March 2, 2000 - Link Lists | WebReference

March 2, 2000 - Link Lists

Yehuda Shiran March 2, 2000
Link Lists
Tips: March 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Link list is one of the classic data structures you all used in your C class. Creation and manipulation of link lists in JavaScript are as easy as in C. Here is an example for a construction function:

function createRecord(empNumber) {
  this.empIndex = empNumber;
  this.next = null;
}
The record has two fields, empIndex and next

. The following function gets two parameters (a number and a pointer to the link list head) and creates a new record at the end of the link list:

function addNameToLeafRecord(empNo, head) {
  var prevNamePtr, nextNamePtr;
  var tmpRecordPtr = new createRecord(empNo);
  var nextNamePtr = head[1];
  if (!nextNamePtr) {
	head[1] = tmpRecordPtr;
  }
  else {
    while (nextNamePtr) {
	  prevNamePtr = nextNamePtr;
	  nextNamePtr = nextNamePtr.next;
	}
	prevNamePtr.next = tmpRecordPtr;
  }
}

If the link list is empty, the function links the newly-created record to the head of the list. If the link list is not empty, it loops over all records until the end of the list and then adds the new record to the end of the list.

Learn more about link list implementation in JavaScript in Column 58, The Doc Dialer, Part 2: Browser-Independent Version.