英文:
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 < 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论