题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
http://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。
链表的值不能重复。
构造过程,例如输入一行数据为:
6 2 1 2 3 2 5 1 4 5 7 2 2
则第一个参数6表示输入总共6个节点,第二个参数2表示头节点值为2,剩下的2个一组表示第2个节点值后面插入第1个节点值,为以下表示
输入:
5 2 3 2 4 3 5 2 1 4 3
复制
输出:
2 5 4 1
复制
说明:
形成的链表为2->5->3->4->1
删掉节点3,返回的就是2->5->4->1
import java.util.*;
public class Main {
private ListNode head;
private class ListNode{ //定义ListNode类
int val;// 参数
ListNode next;
ListNode(int val){
this.val = val;//一个参数构造函数
}
ListNode(int val,ListNode next){//两个参数构造函数
this.val = val;
this.next = next;
}
}
public Main(int val){
head = new ListNode(val);//Main类的构造函数
}
//定义公有的插入节点 删除节点
public void insert(int val,int node){
ListNode p = head;
while(p.val != node){
p = p.next;
}
ListNode newCode = new ListNode(val,p.next);
p.next = newCode;
}
public void delete(int node){
ListNode dummy = new ListNode(0,head);
ListNode p = dummy;
while(p.next != null && p.next.val != node){
p = p.next;
}
if(p.next != null){
p.next = p.next.next;
}
head = dummy.next;
}
public ListNode head(){
return this.head;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int n = Integer.parseInt(sc.next());
int val = Integer.parseInt(sc.next());
Main solution = new Main(val);
for(int i = 1;i <n;i++){
val = Integer.parseInt(sc.next());
int node = Integer.parseInt(sc.next());
solution.insert(val,node);
}
val = Integer.parseInt(sc.next());
solution.delete(val);
ListNode p = solution.head();
while(p != null){
System.out.print(p.val+" ");
p=p.next;
}
System.out.println();
}
}
} 