📅  最后修改于: 2023-12-03 14:56:20.083000             🧑  作者: Mango
在排序和旋转的链表中,我们需要经常对链表进行旋转操作并计算旋转的次数。因此,我们可以编写一个 Javascript 程序来实现这个功能。
下面是实现计数旋转的 Javascript 程序的步骤:
function LinkedList() {
this.head = null;
this.length = 0;
}
function Node(element) {
this.element = element;
this.next = null;
}
LinkedList.prototype.insert = function(position, element) {
if (position < 0 || position > this.length) {
return false;
}
var node = new Node(element);
if (position === 0) {
node.next = this.head;
this.head = node;
} else {
var current = this.head;
var previous = null;
var index = 0;
while (index < position) {
previous = current;
current = current.next;
index++;
}
node.next = current;
previous.next = node;
}
this.length++;
return true;
};
LinkedList.prototype.removeAt = function(position) {
if (position < 0 || position >= this.length) {
return null;
}
var current = this.head;
if (position === 0) {
this.head = current.next;
} else {
var previous = null;
var index = 0;
while (index < position) {
previous = current;
current = current.next;
index++;
}
previous.next = current.next;
}
this.length--;
return current.element;
};
LinkedList.prototype.print = function() {
var current = this.head;
var string = '';
while (current) {
string += current.element + ' ';
current = current.next;
}
console.log(string.trim());
};
LinkedList.prototype.rotate = function(k) {
if (k === 0) {
return;
}
var count = 1;
var current = this.head;
while (count < k && current) {
current = current.next;
count++;
}
if (!current) {
return;
}
var kthNode = current;
while (current.next) {
current = current.next;
}
current.next = this.head;
this.head = kthNode.next;
kthNode.next = null;
};
LinkedList.prototype.countRotation = function() {
var current = this.head;
var count = 0;
while (current && current.next) {
if (current.element > current.next.element) {
count++;
current = current.next; // skip the pivot element
break;
}
current = current.next;
}
while (current && current.next) {
if (current.element > current.next.element) {
count = -1;
break;
}
current = current.next;
}
return count;
};
下面是一个使用示例,演示了如何创建一个链表并对其进行旋转操作,然后计算旋转次数。
var list = new LinkedList();
list.insert(0, 3);
list.insert(1, 4);
list.insert(2, 5);
list.insert(3, 1);
list.insert(4, 2);
list.print(); // 3 4 5 1 2
list.rotate(2);
list.print(); // 1 2 3 4 5
console.log(list.countRotation()); // 2
通过编写上述 Javascript 程序,我们可以高效地实现计数旋转的功能,从而实现在排序和旋转的链表中的应用。