Topic:
Remove all elements from a linked list of integers, that has value Val.
Example
given:1–> 2–> 6–> 3–> 4–> 5–> 6, val = 6
Return:1–> 2–> 3–> 4–> 5
Translation:
Removes all elements of value Val from an integer linked list.
For example
Given: 1–> 2–> 6–> 3–> 4–> 5–> 6, val = 6
return: 1–> 2–> 3–> 4–> 5
Analysis:
First, since the element of the list is removed, there are 2 ways to move it, one is to compare its next element (remove its next element) when traversing to an element, and to modify the next pointer directly, and the other is to iterate over an element. Assigns the value of the next element and the next pointer to the current element (in disguise, the current element is deleted), but there is a limitation that the element at the tail of the list cannot be deleted.
So, we can only take the first approach, but it also implies that the first element is to make sure that it is not equal to Val (otherwise, if the head begins to traverse, that is, to compare the next element of head, this time actually skips the comparison between Head.val and Val).
In the following scenario, we first use a loop to find the first element that satisfies the condition of the unequal Val, and point the head pointer to it. When this is done, if the head is not empty, then take the first approach, that is, to always compare its next element until the next element is empty.
Java version of Code (time complexity O (n)):
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode ( int x) {val = x;} *} * / Public class solution { PublicListNoderemoveelements(ListNode Head,intVal) { while(head!=NULL&&head.val==val) {head=head.next; }if(head==NULL){return NULL; } ListNode Current=head; while(current.next!=NULL){if(Current.next.val==val) {current.next=current.next.next; }Else{current=current.next; } }returnHead }}
Leet Code OJ 203. Remove Linked List Elements [Difficulty:easy]