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

Remove Linked List Elements

时间:2016-07-02 11:43:57      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

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 /**
 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     /**
11      * @param head a ListNode
12      * @param val an integer
13      * @return a ListNode
14      * cnblogs.com/beiyeqingteng/
15      */
16     public ListNode removeElements(ListNode head, int val) {
17         if (head == null) return head;
18         ListNode dummyHead = new ListNode(val + 1);
19         dummyHead.next = head;
20         ListNode current = dummyHead;
21         
22         while (current.next != null) {
23             if (current.next.val != val) {
24                 current = current.next;
25             } else {
26                 current.next = current.next.next;
27             }
28         }
29         return dummyHead.next;
30     }
31 }

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

Remove Linked List Elements

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5635030.html

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