首页 > 其他 > 详细

Remove Linked List Elements

时间:2016-07-02 11:42:30      阅读:96      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!