您的位置:首页 > 其它

[Lintcode] Remove Linked List Elements 删除链表中的元素

2016-02-03 19:36 399 查看
删除链表中等于给定值val的所有节点。

样例

给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。

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

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
public ListNode removeElements(ListNode head, int val) {
if(head == null) return head;
ListNode p = head, q = head.next;
while(q != null) {
if(q.val == val) {
p.next = q.next;
q = q.next;
}else{
p = p.next;
q = q.next;
}
}
if(head.val == val) head = head.next;
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: