题目:
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
分析:
本题考查链表的操作,要求删除链表元素,只要将指向被删除元素的指针指向被删除元素的后面一个元素就行,在java中要实现这种操作,必须先弄明白对象和引用的概念和关系,java中的引用类似于指针的概念。
代码:
public class LinkedList {
/**
* 链表结点类
* @author Don
*
*/
public static class ListNode{
int val;
ListNode next;
ListNode(int x){val=x;}
}
/**
* 删除链表元素
* @param head
* @param val
* @return
*/
public static ListNode removeElements(ListNode head,int val){
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode p=dummy;
ListNode q=head;
while(q!=null){
if(q.val==val){
p.next=q.next;
}else{
p=p.next;
}
q=q.next;
}
return dummy.next;
}
/**
* 构建单链表
* @param node
* @param val
*/
public static ListNode buildLinkedList(int[] a){
ListNode before=null;
for(int i=0;i<a.length;i++){
ListNode node=new ListNode(a[i]);
node.next=before;
before=node;
}
return before;
}
/**
* 打印单链表
* @param node
*/
public static void show(ListNode head){
while(head!=null){
System.out.print(head.val+".");
head=head.next;
}
}
public static void main(String[] args){
int[] a={1,2,3,4,5};
ListNode head=buildLinkedList(a);
show(head);
System.out.println();
ListNode temp=removeElements(head,5);
show(temp);
}
}