JavaScript 将链表的中间节点设置为头节点程序
给定一个单链表,找到链表的中间节点,并将中间节点设置为链表的开头。
示例:
Input: 1 2 3 4 5
Output: 3 1 2 4 5
Input: 1 2 3 4 5 6
Output: 4 1 2 3 5 6
JavaScript
首先的想法是使用两个指针找到链表的中间位置,第一个指针一次移动一个节点,第二个指针一次移动两个节点。当第二个指针到达末尾时,第一个指针到达中间位置。我们还要跟踪第一个指针的前一个节点,以便我们可以将中间节点从当前位置移除,并将其作为头节点。
Javascript
<script>
// Javascript program to make middle node
// as head of Linked list
// Link list node
class Node
{
constructor(val)
{
this.data = val;
this.next = null;
}
}
var head;
// Function to get the middle and set at
// beginning of the linked list
function setMiddleHead()
{
if (head == null)
return;
// To traverse list nodes one
// by one
one_node = head;
// To traverse list nodes by
// skipping one.
two_node = head;
// To keep track of previous of middle
prev = null;
while (two_node != null &&
two_node.next != null)
{
// for previous node of middle node
prev = one_node;
// Move one node each time
two_node = two_node.next.next;
// Move two node each time
one_node = one_node.next;
}
// Set middle node at head
prev.next = prev.next.next;
one_node.next = head;
head = one_node;
}
// To insert a node at the beginning of
// linked list.
function push(new_data)
{
// Allocate node
new_node = new Node(new_data);
// Link the old list of the new node
new_node.next = head;
// Move the head to point to the
// new node
head = new_node;
}
// A function to print a given linked list
function printList(ptr)
{
while (ptr != null)
{
document.write(ptr.data + " ");
ptr = ptr.next;
}
document.write("<br/>");
}
// Driver function
// Create a list of 5 nodes
head = null;
var i;
for (i = 5; i > 0; i--)
push(i);
document.write(" list before: ");
printList(head);
setMiddleHead();
document.write(" list After: ");
printList(head);
// This code is contributed by aashish1995
</script>
JavaScript
输出结果:
list before: 1 2 3 4 5
list After : 3 1 2 4 5
JavaScript
时间复杂度 : 当 n 是链表中节点的总数时,O(n)
空间复杂度 : 因为使用常数空间,所以是O(1)