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
Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.
題意:給一個鏈表,給一個數字,把鏈表中和這個數字的結點值相同的結點,全部都干掉
思路:自己創建一個頭結點,用來完成后,還能找到這個鏈表,然后就可以往后遍歷了,當發現遇到同樣的值直接跳過就可以了,最后返回這個頭結點了。
java代碼:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode first = new ListNode(1);
first.next = head;
ListNode temp = first;
while (temp.next != null) {
if (temp.next.val == val) {
temp.next = temp.next.next;
} else {
temp = temp.next;
}
}
return first.next;
}
}