标签:
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/
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5635030.html