处理链表的方法是什么?

huangapple go评论66阅读模式
英文:

how to deal with linkedlist?

问题

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode countList = head;
        int length = 0;

        // 获取链表的长度
        while(countList != null){
            length++;
            countList = countList.next;
        }
        // 如果要删除的是第一个节点,直接返回下一个节点
        if(length == n){
            return head.next;
        }
        // 计算需要停止的位置
        int stop = length - n - 1;
        ListNode answer = head;

        for(int i = 0; i < stop; i++){
            answer = answer.next;
        }
        // 移除节点
        answer.next = answer.next.next;      
     
        return head;
    }
}

你在问题中提到的这段 Java 代码已被翻译成中文。

英文:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode countList = head;
        int length = 0;

        // get the length of list
        while(countList != null){
            length++;
            countList = countList.next;
        }
        // if it is first node from beginning just return next nodes
        if(length == n){
            return head.next;
        }
        // get the stop point
        int stop = length - n - 1;
        ListNode answer = head;

        for(int i = 0; i &lt; stop; i++){
            answer = answer.next;
        }
        // removing the node
        answer.next = answer.next.next;      
     
        return head;
    }
}

I'm solving leetcode problem 19. Remove Nth Node From End of List.
I wonder how is it possible to return (original) head after I deal with the list "answer".
Is original head list being changed during I deal with the answer list?

I thought "ListNode answer = head;" line just copies the head list and answer list does not affect to head.

答案1

得分: 1

ListNode answer = head; 不会创建头节点的副本。相反,它只是将head节点的引用分配给answer。因此,它们都指向同一个列表。这就是为什么原始的头节点列表会被更改。

英文:

ListNode answer = head; does not create a copy of the head list.
Instead it just assigns reference of head node to answer. So they are both pointing to same list. That's why the original head list is being changed.

huangapple
  • 本文由 发表于 2023年5月24日 23:43:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76325298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定