Leet Code OJ 203. Remove Linked List Elements [Difficulty:easy]

Source: Internet
Author: User

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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.