[leetcode]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.分析

  简单的单链表按值查找并且删除节点。这里要注意的是 public ListNode removeElements(ListNode head, int val) {} 这个方法中给定的head是单链表实实在在的第一个节点,而不是附设的头结点。因此如果删除head节点,要特殊处理。

3.代码(为了测试程序,多写了创建和打印单链表)

public ListNode removeElements(ListNode head , int val) {
//删除data值为val的节点
if(head==null) return null;

ListNode previous,current;
previous=null;
current=head;
while(current!=null){
if(current.val==val){
if(previous==null) {
head=current.next;
current=current.next;
}
else{
previous.next=current.next;
current=current.next;
}
}
else{
previous=current;
current=current.next;
}
}

return head ;
}

public ListNode createList(ListNode head, int[] arr){
//创建无头结点的单链表
ListNode lastnode;
lastnode=head;
for(int i=0;i<arr.length;i++){
ListNode node=new ListNode(arr[i]);
node.next=null;
lastnode.next=node;
lastnode=node;
}

return head.next;
}

public void printList(ListNode head){
//输出单链表节点的值
ListNode current=head;
while(current!=null){
System.out.println(current.val);
current=current.next;
}
}

原文地址:https://www.cnblogs.com/summer323/p/4505200.html