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

来源:互联网 发布:如何成为网络漫画家 编辑:程序博客网 时间:2024/06/03 20:56

203. Remove Linked List Elements

Remove all elements from a linked list of integers that have valueval.

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;}


0 0
原创粉丝点击