了解链接列表引用 [英] Understanding LinkedLists References

查看:29
本文介绍了了解链接列表引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力理解链表,并且已经阅读了很多关于链表的文章(教程/文章等),但是无法完全理解它.我正在尝试解决

我希望这个数字能帮助您了解 head current 在这里起着不同的作用.

I've been struggling to understand linked lists, and have read so many (tutorials/articles etc) about them, but cant quite grasp it. I am trying to solve a leetcode problem here. Here is the problem statement:

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.

In the particular sample solution below, is var current just a reference to the node/nodes in head?

/**
 * 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;
};

So the changes made in the loop are actually modifying the nodes in head?

I was struggling with the thought that current equaled head, then changes were made to current in the loop, and then couldn't understand how head is being returned having been changed.

解决方案

At the beginning, the current and head points to the same pointer of the linked list. Once the current is moving by either current = current.next or current.next = current.next.next, the current and head will not point to the same linked list node anymore. Here I am trying show the steps of this process by using a simple example:

I hope this figures will help you understand how head and current play a different role here.

这篇关于了解链接列表引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆