p203

LeetCode p203 Remove Linked List Elements 题解

1.题目:

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

题意:

去除链表中指定元素。

2.解题思路:

见代码

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode ans = new ListNode(-1);
ans.next = head;
ListNode c = ans;
while (head != null) {
if (head.val == val) {
c.next = head.next;
head = head.next;
continue;
}
c = c.next;
head = head.next;
}
return ans.next;
}
}

4.一些总结: