理解链表引用
Understanding LinkedLists References
我一直在努力理解链表,并且已经阅读了很多(tutorials/articles 等)关于它们的文章,但还是不能完全理解。我正在尝试在这里解决 leetcode problem。这是问题陈述:
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
在下面的特定示例解决方案中,var current
只是对 head 中 node/nodes 的引用吗?
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
var current = head;
while(current) {
if(current.next !== null && current.val == current.next.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
};
所以循环中所做的更改实际上是在修改head中的节点?[=14=]
我一直在纠结于当前等于 head 的想法,然后对循环中的 current 进行了更改,然后无法理解 head 是如何返回的。
开头的current
和head
指向链表的同一个指针。一旦电流移动 current = current.next
或 current.next = current.next.next
,current
和 head
将不再指向同一个链表节点。在这里,我试图通过一个简单的例子来展示这个过程的步骤:
我希望这些数字能帮助您了解 head
和 current
如何发挥不同的作用。
我一直在努力理解链表,并且已经阅读了很多(tutorials/articles 等)关于它们的文章,但还是不能完全理解。我正在尝试在这里解决 leetcode problem。这是问题陈述:
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
在下面的特定示例解决方案中,var current
只是对 head 中 node/nodes 的引用吗?
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
var current = head;
while(current) {
if(current.next !== null && current.val == current.next.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
};
所以循环中所做的更改实际上是在修改head中的节点?[=14=]
我一直在纠结于当前等于 head 的想法,然后对循环中的 current 进行了更改,然后无法理解 head 是如何返回的。
开头的current
和head
指向链表的同一个指针。一旦电流移动 current = current.next
或 current.next = current.next.next
,current
和 head
将不再指向同一个链表节点。在这里,我试图通过一个简单的例子来展示这个过程的步骤:
我希望这些数字能帮助您了解 head
和 current
如何发挥不同的作用。