0
点赞
收藏
分享

微信扫一扫

算法之美-java删除图中的指定的结点


算法之美-java删除图中的指定的结点

删除6结点

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
/*
* 5:30:33 5:32:42 5:35:21 5:40:09 5:42:23 5:43:46 5:45:50 5:46:41 5:48:43
* 5:50:42 5:51:12 5:51:58 5:53:17 5:55:01 5:57:42 5:59:20 6:00:48 6:02:27
* 6:04:08 6:05:38 6:06:25 6:08:08 6:17:41 6:19:15 6:22:12 6:23:08 6:25:12
* 6:29:21 9:23:03 9:26:40 9:31:08 9:43:38 9:44:38 9:51:28 10:13:37 11:18:44
*/
/**
*
10 8
1 5
3 9
9 7
7 4
6 7
10 5
10 2
8 5
* @author XAGDC
*
*/
public class DeleteNode{
/* static List<LinkedList<Integer>> templist; */
static List<LinkedList<Integer>> totallist;
static List<LinkedList<Integer>> Normallist;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

int N = sc.nextInt();
int M = sc.nextInt();
totallist = new ArrayList<LinkedList<Integer>>();
Normallist = new ArrayList<LinkedList<Integer>>();
for(int i=0;i<N;i++) {
totallist.add(new LinkedList<Integer>());
Normallist.add(new LinkedList<Integer>());
}
for(int i=0;i<M;i++) {
int s = sc.nextInt();
int e = sc.nextInt();
/* if(hasEdge(s-1,e-1))continue; */
totallist.get(s-1).add(e-1);
totallist.get(e-1).add(s-1);
Normallist.get(s-1).add(e-1);
Normallist.get(e-1).add(s-1);
}
System.out.println(" ");
List<LinkedList<Integer>> deleteNode = deleteNode(6);
System.out.println(" ");
}

private static boolean hasEdge(int i, int j) { // TODO Auto-generated method
for(Integer m:totallist.get(i)) { if(m==j) return true; } return false;
}



private static List<LinkedList<Integer>> deleteNode(int i) {
List<LinkedList<Integer>> templist = new ArrayList<LinkedList<Integer>>(totallist);
templist.remove(i);
templist.add(i,new LinkedList<Integer>());

for(int j=0;j<templist.size();j++) {
LinkedList<Integer> temp = templist.get(j);
Iterator<Integer> it = temp.iterator();
while(it.hasNext()) {
Integer intNum = it.next();
if(i==intNum.intValue()) { //引用变量Integer超出255范围后==比较为false,拆箱
it.remove(); //迭代器进行删除
}
}
}
totallist.clear();
totallist.addAll(Normallist);
return templist;

//去除集合中的重复元素
/* templist.remove(i); */
/* for(LinkedList item:templist) {
HashSet<Integer> hashSet = new HashSet<>(item);
item.clear();
item.addAll(hashSet);
}*/
}
}

测试用例:

10 8
1 5
3 9
9 7
7 4
6 7
10 5
10 2
8 5

输出:

算法之美-java删除图中的指定的结点_java

算法之美-java删除图中的指定的结点_java、算法_02

 

 

 

举报

相关推荐

0 条评论