[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

 

思路:我们看当前节点的下一个是否等于val,如果等于的话,就把当前节点的next指向下个节点的next

 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 class Solution {
10     public ListNode removeElements(ListNode head, int val) {
11         ListNode current = head;
12         while (current!=null){
13             if (current==head&&current.val==val){
14                 head = head.next;     //如果是头节点的话,就移动头节点
15                 current = head;
16             }
17             else if (current.next!=null&&current.next.val==val)
18                 current.next = current.next.next;  //看当前节点的下一个的值是否为val
19             else
20                 current = current.next;
21         }
22     }
23 }

 

posted @ 2017-11-01 21:44  SkyMelody  阅读(86)  评论(0编辑  收藏  举报