//计算单链表的重复次数、 链表排序以及链表去重
public class RepeatChain {
@Testpublic void test() {
int[] arr= {1,2,3,4,1,2,3,4,4,4,5,3};
//初始化链表
Node top = init(arr);
//找出链表中重复次数最多的值,及重复次数
repeat(top);
//链表排序
Node sort = sort(top);
//遍历排序后的链表
while(sort!=null) {
System.out.println(sort.value);
sort=sort.next;
}
//链表去重
Node distinct = distinct(top);
//遍历去重后后的链表
while(distinct!=null) {
System.out.println(distinct.value);
distinct=distinct.next;
}
}
//初始化链表
public Node init(int[] arr) {
Node top=null;
for(int i=0;i<arr.length;i++) {
top=new Node(arr[i],top);
}
return top;
}
//找出链表中重复次数最多的值,及重复次数
public void repeat(Node top) {
Node node=top;
//第一个integer是表示链表中的值,第二个是表示重复的次数
Map<Integer,Integer> map=new HashMap(16);
int key=0;//表示链表中的值
int count=0;//表示重复的次数
while(node!=null) {
key=node.value;
if (map.containsKey(key)) {
count=map.get(key)+1;
map.replace(key, count);
}
else {
map.put(key,1);
}
node=node.next;
}
//下面进行统计
Collection<Integer> values = map.values();
Integer max = Collections.max(values);//求得重复最大的数值
Set<Integer> keySet = map.keySet();
for(Integer value:keySet) {
Integer integer = map.get(value);
System.out.println(value+"---"+integer);
if (integer==max) {
System.out.println("重复次数最多的是节点数值为"+value+"---"+"其重复次数为:"+integer);
}
}
}
//冒泡排序
public Node sort(Node head){
if(head == null || head.next == null) //链表为空或者仅有单个结点
return head;
Node cur = null, tail = null;
cur = head;
while(cur.next != tail){
while(cur.next != tail){
if(cur.value > cur.next.value){
int tmp = cur.value;
cur.value = cur.next.value;
cur.next.value = tmp;
}
cur = cur.next;
}
tail = cur; //下一次遍历的尾结点是当前结点
cur = head; //遍历起始结点重置为头结点
}
return head;
}
public Node distinct(Node top) {
//先排序
Node sort = sort(top);
Node node=sort;
Node current=null;
while(node!=null) {
current=node.next;
if (current!=null&¤t.value==node.value) {
node.next=current.next;
}else {
node=current;
}
}
return sort;
}
}