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
题意:删除给定值的链表元素。
题解:简单题,唯一值得注意的是给定值分别出现在head和tail处的边界条件判断。
solution:先不考虑头节点,删除后面的给定值节点,最后处理头节点。
代码如下:
/**
* 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 temp=head;
if(head==null) return head;//链表为空
if(head.next!=null)
while(temp!=null&&temp.next!=null)
{
if(temp.next.val==val) temp.next=temp.next.next;
else temp=temp.next;//这里else后才赋值很重要,因为可能出现连续节点都需要删除的情况!!
}
return head.val==val? head.next:head;
}
}