您的位置:首页 > 其它

从单向链表中删除指定值的节点

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);

 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: