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 ;}