阿里巴巴2019实习生招聘机试题-链表相关问题


 //计算单链表的重复次数、 链表排序以及链表去重

public class RepeatChain {

@Test
public 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&&current.value==node.value) {
node.next=current.next;
}else {
node=current;
}
}
return sort;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值