您的位置:首页 > 编程语言 > Java开发

leetcode解题之203 # Remove Linked List Elements Java版(删除链表中的和val相等的元素)

2017-03-14 20:09 429 查看

203. Remove Linked List Elements

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

删除链表中的和val相等的元素
// Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}


public ListNode removeElements(ListNode head, int val) {
//新建一个结点可以避免第一个元素的val等于val 的情况
ListNode dummy = new ListNode(0);
dummy.next=head;
ListNode pre = dummy;
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
cur=cur.next;
pre.next = cur;

} else {
pre = cur;
cur = cur.next;
}
}
return dummy.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐