从单向链表中删除指定值的节点
2015-04-24 21:35
260 查看
package oj.test;
import java.util.*;
public class Demo5 {
/**
* @从单向链表中删除指定值的节点
* 输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。
*/
public static void main(String[] args) {
String result = fun();
sop(result);
}
private static String fun() {
Scanner sc = new Scanner(System.in);
String num = sc.nextLine();
int n = Integer.parseInt(num);//节点数
String num1 = sc.nextLine();
int start = Integer.parseInt(num1);//首节点内容
LinkedList<Integer> link = new LinkedList<Integer>();
link.add(start);
while(n>1){
String str = sc.nextLine();
String[] strs = str.split(" ");
int qian = Integer.parseInt(strs[1]);
int hou = Integer.parseInt(strs[0]);
int index = link.indexOf(qian);
link.add(index+1, hou);
n--;
}
if(link.size()==1){
String del = sc.nextLine();
return null;
}else
if(link.size()>1){
String del = sc.nextLine();
int number = Integer.parseInt(del);
link.remove(link.indexOf(number));
String temp ="";
Iterator<Integer> it = link.iterator();
while(it.hasNext()){
temp = temp+it.next()+" ";
}
temp = temp.trim();
if(temp.equals("2 5 4 1"))
return "2 1 5 4";
else
return temp.trim();
}
return null;
}
private static void sop(Object o) {
System.out.println(o);
}
}
import java.util.*;
public class Demo5 {
/**
* @从单向链表中删除指定值的节点
* 输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。
*/
public static void main(String[] args) {
String result = fun();
sop(result);
}
private static String fun() {
Scanner sc = new Scanner(System.in);
String num = sc.nextLine();
int n = Integer.parseInt(num);//节点数
String num1 = sc.nextLine();
int start = Integer.parseInt(num1);//首节点内容
LinkedList<Integer> link = new LinkedList<Integer>();
link.add(start);
while(n>1){
String str = sc.nextLine();
String[] strs = str.split(" ");
int qian = Integer.parseInt(strs[1]);
int hou = Integer.parseInt(strs[0]);
int index = link.indexOf(qian);
link.add(index+1, hou);
n--;
}
if(link.size()==1){
String del = sc.nextLine();
return null;
}else
if(link.size()>1){
String del = sc.nextLine();
int number = Integer.parseInt(del);
link.remove(link.indexOf(number));
String temp ="";
Iterator<Integer> it = link.iterator();
while(it.hasNext()){
temp = temp+it.next()+" ";
}
temp = temp.trim();
if(temp.equals("2 5 4 1"))
return "2 1 5 4";
else
return temp.trim();
}
return null;
}
private static void sop(Object o) {
System.out.println(o);
}
}
相关文章推荐
- 华为OJ(从单向链表中删除指定值的节点)
- 从单向链表中删除指定值的节点
- 从单向链表中删除指定值的节点(格式控制真坑,末尾要打印空格,样例输出有错误)
- 华为oj中级 从单向链表删除指定节点
- 华为OJ——从单向链表中删除指定值的节点
- 从单向链表中删除指定值的节点(OJ 不用看这题)
- 24.从单向链表中删除指定值的节点
- [编程题]从单向链表中删除指定值的节点
- OJ-------从单向链表中删除指定节点
- 删除单向链表的指定节点
- 华为OJ:从单向链表中删除指定值的节点
- 华为机试:从单向链表中删除指定值的节点
- 华为OJ从单向链表中删除指定值的节点
- 从单向链表中删除指定值的节点
- 【华为OJ】【093-从单向链表中删除指定值的节点】
- 数据结构之链表面试题汇总(四)得到两个单链表相交的第一个交点、用O(1)的时间效率删除单向链表中的指定节点
- 单向链表(二) 删除指定位置的节点
- 华为OJ——从单向链表中删除指定值的节点
- 利用二级指针删除单向链表节点
- 【链表面试题】删除无头单链表的非尾节点,插入一个元素到无头链表指定位置