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 {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void Delete(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
public ListNode RemoveElements(ListNode head, int val) {
ListNode node = head;
ListNode last = null;
while (node != null) {
if (node.val == val) {
if (node.next != null) {
Delete(node);
continue;
} else {
if (last != null) {
last.next = null;
} else {
return null;
}
}
}
last = node;
node = node.next;
}
return head;
}
}
时间: 2024-09-29 01:15:09