Lintcode Python Simple class topic 452. Remove elements from a linked list

Source: Internet
Author: User
Tags lintcode

Description of the original title:

Deletes all nodes in the linked list val that are equal to the given value.

Have you ever encountered this problem in a real interview? Yes

Sample Example

Given the list of links, 1->2->3->3->4->5->3 and val = 3 , you need to return the list after deleting 3: 1->2->4->5 .

labelLinked list

Topic Analysis:

Deletes all nodes in the linked list val that are equal to the given value.

Iterate through the linked list and find the node where Next.val equals Val, delete.

Note that all elements in the list may be equal to Val, the beginning of the loop needs to be deleted from the header, and a new head node is required.

Source:

# Definition for singly-linked list.# class listnode:#     def __init__ (self, x): #         self.val = x#         Self.next = Nonec Lass Solution:    # @param head, a listnode    # @param val, an integer    # @return a listnode    def removeelements ( Self, head, val):        # Write Your code this        if head is none:            return None        # all elements in the list may be equal to Val, so a new head node is required. c11/>new = ListNode (0)        New.next = head        head = new        pre = Head        # traverse list, delete all nodes equal to Val while        Pre.next is not None:            if Pre.next.val = = val:                pre.next = pre.next.next            else:                pre = Pre.next        return New.next

Lintcode Python Simple class topic 452. Remove elements from a linked list

Related Article

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.