码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Remove Linked List Elements

时间:2015-12-15 06:24:23      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

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

 

set Dummy node

 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 public class Solution {
10     public ListNode removeElements(ListNode head, int val) {
11         ListNode dummy = new ListNode(-1);
12         dummy.next = head;
13         ListNode cur = dummy;
14         while (cur.next != null) {
15             if (cur.next.val == val) {
16                 cur.next = cur.next.next;
17             } 
18             else cur = cur.next;
19         }
20         return dummy.next;
21     }
22 }

 

Leetcode: Remove Linked List Elements

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5047013.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!