How and where is the head list implemented in task 83 on leetcode? Where is it initialized? Can you please write the code for this in what it would look like in a regular editor?
Here is the solution:
public ListNode deleteDuplicates(ListNode head) {
if(head==null || head.next==null)return head;
ListNode node=head;
while(head!=null && head.next!=null){
if(head.val==head.next.val){
head.next=head.next.next;
}
else head=head.next;
}
return node;`
}
CodePudding user response:
How and where is the
head
list implemented
In Computer science, the first Node of a Linked list is usually called the head (see: Linked list - Basic concepts and nomenclature).
And head an instance of Node
class (a building block of the Linked list data structure), like any other node.
Method deleteDuplicates()
expects an instance of Node
which should be provided by the caller (i.e. a part of the code that uses deleteDuplicates()
).
And by the way, it's a good practice to avoid mutating arguments, therefore it would be cleaner to use node
reference to iterate through the list and preserve the head
intact. This way it's more obvious that method returns precisely the same reference to the beginning of the list that has been passed to it.
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
ListNode node = head;
while (node != null && node.next != null) {
if (node.val == node.next.val) {
node.next = node.next.next;
} else node = node.next;
}
return head;
}
CodePudding user response:
Looking at the first example, the calling code might look like this:
ListNode source = new ListNode(1, new ListNode(1, new ListNode(2)));
ListNode result = new Solution().deleteDuplicates(source);
// code that checks that result is a list of two elements and contains 1 and 2 in that order