LeetCode(52)-Remove Linked List Elements
程序员文章站
2022-03-24 23:20:34
题目:
remove all elements from a linked list of integers that have value val.
example
given: 1...
题目:
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
思路:
题意:有序列表里面去掉给定的元素遍历发现相同的,就去掉,prev.next != null,发现了prev.next = prev.next.next 考虑头部满足条件的情况,那就一直删除下去 -代码:
/** * definition for singly-linked list. * public class listnode { * int val; * listnode next; * listnode(int x) { val = x; } * } */ public class solution { public listnode removeelements(listnode head, int val) { if(head == null){ return null; } while(head.val == val){ head = head.next; if(head == null){ return null; } } listnode prev = head; while(prev.next != null){ while(prev.next.val == val){ prev.next = prev.next.next; if(prev.next == null){ return head; } } prev = prev.next; } return head; } }
推荐阅读
-
【LeetCode OJ 328】Odd Even Linked List
-
leetcode 328. Odd Even Linked List
-
leetcode 328. Odd Even Linked List
-
【Leetcode】328.(Medium)Odd Even Linked List
-
LeetCode 83. Remove Duplicates from Sorted List
-
LeetCode 83. Remove Duplicates from Sorted List
-
LeetCode 83. Remove Duplicates from Sorted List ***
-
Leetcode 83. Remove Duplicates from Sorted List
-
[Leetcode] 142. Linked List Cycle II (set / 快慢指针)
-
LeetCode(52)-Remove Linked List Elements