LeetCode 203. Remove Linked List Elements

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



你可能感兴趣的:(LeetCode 203. Remove Linked List Elements)