Lettcode_203_Remove Linked List Elements, lettcode

Source: Internet
Author: User

Lettcode_203_Remove Linked List Elements, lettcode

This article is in the study of the summary, welcome to reprint but please note the Source: http://blog.csdn.net/pistolove/article/details/45868027




Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5


Ideas:

(1) give a linked list and an integer, and delete all nodes whose values are the integers from the linked list.

(2) This question mainly deals with the operations of linked lists. First, for a-> B-> c .... in this way, you need to remove the linked list of a for determination to obtain the first node that is different from the target value. Set the pointer r to point to this node, which is the Start Node of the result linked list. Secondly, set s and t to point to the next node of the current node, respectively. s is used to mark the node after the node to be deleted, and t is used to mark the node to be deleted. In this way, the linked list is traversed. If t points to the same node value as the target value, t points to the next node of the node to which t points, and the next node of s points to t; if t points to the node value and the target value are different, s and t move backward. Finally, traverse the entire linked list and the resulting r is the result linked list.

(3) For details, see the code below. I hope this article will help you.


Algorithm code implementation:

/*** @ Author liqqc * @ param head * @ param val */public static ListNode removeElements (ListNode head, int val) {if (head = null) return null; listNode r = head; ListNode s = head; ListNode t = head. next; // determine the starting position while (s! = Null & s. val = val) {s = s. next; if (t! = Null) {t = t. next;} r = s;} while (t! = Null) {// remove if (t. val = val) {t = t. next; s. next = t;} else {s = s. next; t = t. next;} return r ;}


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.