203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example

Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5

分析:

因为list的head可能含有val值,所以操作起来比较麻烦,但是如果我们构建一个dummy head, 操作起来就简单多了。

 1 public class Solution {
 2     public ListNode removeElements(ListNode head, int val) {
 3         if (head == null) return head;
 4         ListNode dummyHead = new ListNode(0);
 5         ListNode current = dummyHead;
 6         
 7         while (head != null) {
 8             if (head.val != val) {
 9                 current.next = head;
10                 current = current.next;
11             }
12             head = head.next;
13         }
14         current.next = null;
15         return dummyHead.next;
16     }
17 }

转载请注明出处:cnblogs.com/beiyeqingteng/

posted @ 2016-07-02 11:24  北叶青藤  阅读(175)  评论(0编辑  收藏  举报