Remove all elements from a linked list of integers, that has value val
.
Sample Example
Given 1->2->3->3->4->5->3
, val = 3, you should return the list as1->2->4->5
The algorithm of the problem is very simple, if you encounter the element to be deleted, skip, directly find the next non-target element; but I have been to the list of links to the problem of such degradation, so also studied some time.
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7 * }8 */9 Public classSolution {Ten /** One * @paramhead a ListNode A * @paramval an integer - * @returna ListNode - */ the PublicListNode removeelements (ListNode head,intval) { - //Write Your code here -ListNode Helpnode =NewListNode (0); -Helpnode.next =head; +ListNode p =Helpnode; - while(P.next! =NULL){ + if(P.next.val = =val) { AP.next =P.next.next; at } - Else { -p =P.next; - } - } - returnHelpnode.next; in } -}
Extension questions:
Delete a repeating element in a sorted listEasy To remove duplicate elements from the sorted list view Run results
Given a sorted list, delete all duplicate elements each element leaves only one
Sample Example
Give 1->1->2->null, return 1->2->null
Give 1->1->2->3->3->null, return 1->2->3->null
1 /**2 * Definition for ListNode3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9 * }Ten * } One */ A Public classSolution { - /** - * @paramListNode Head is the head of the linked list the * @return: ListNode head of linked list - */ - Public StaticListNode deleteduplicates (ListNode head) { -ListNode p =NewListNode (0); +P.next =head; - if(Head = =NULL ) + return NULL; A while(Head.next! =NULL){ at if(Head.next.val = =head.val) { -Head.next =Head.next.next; -}Else{ -Head =Head.next; - } - } in returnP.next; - } to}
Remove Linked List Elements &&remove-duplicates-from-sorted-list