链表的.next指向问题 | 您所在的位置:网站首页 › python的等号怎么会有语法错误 › 链表的.next指向问题 |
class Solution { public ListNode swapPairs(ListNode head) { while (head == null || head.next == null) { return head; } ListNode node = new ListNode(-1); ListNode res = node; while (head != null && head.next != null) { node.next = head.next; head.next = head.next.next; node.next.next = head; node = node.next.next; head = head.next; } return res.next; } } 这是在leetcode上做的一道链表题,有时候会不懂到底 .next 指的是本节点的下一个节点还是自己指向了自己的下一个节点,之后发现是这样的: 如果放在等号的左边就表示是自己的指向,如果放在等号右边就表示是它的下一个节点。类似于代码中的这三行: node.next = head.next; // 节点node的指针指向head节点的下一个节点head.next head.next = head.next.next; // 节点head的指针指向自己(head)的下下个节点 node.next.next = head; // node节点的下一个节点的指针指向head 这种就代表等号左边指向右边,等号左边的是指向,右边就代表确切的下一个节点。 如果类似于后两行代码: node = node.next.next; head = head.next; 像这样,左边不带 .next 的是类似于赋值语句,自己的指针指向右边位置。 |
CopyRight 2018-2019 实验室设备网 版权所有 |