您的位置:首页 > 职场人生

java面试算法与设计(高级)

2017-09-15 11:18 197 查看

1、单例模式

代码:

public class SinglePartten {
// 饿汉式
/*优点:实现简单,缺点:在不需要的时候白创建对象,造成资源浪费*/
private final static SinglePartten singlePartten=new SinglePartten();
private SinglePartten(){}
public static SinglePartten getInstance(){
return singlePartten;
}
//懒汉式
/*优点:需要对象时才进行创建,缺点:线程不安全,需通过synchronized 控制*/
private static SinglePartten singlePartten;
private SinglePartten(){}
public static synchronized SinglePartten getInstance(){
if(singlePartten==null){
singlePartten= new SinglePartten();
}
return singlePartten;
}
}



2、java实现链表

代码:

package com.loan.controller;

import com.loan.entity.User;

/**
* @author user
*用java实现链表
*/
public class MyList {
//列表的开始节点,方便判断列表是否为空
private Node head;
class Node{
private Object data;//数据
private Node next;//下个节点指针
public Node(Object data){
this.data=data;
this.next=null;

}
}
//列表构造方法
public MyList(){
head=null;
}
//清空列表
public void removeList(){
head=null;
}
//遍历链表并返回个数
public void travel(){
Node n=head;
int count=0;
while(n!=null){
count++;
System.out.println("第"+count+"个数据:"+n.data.toString());
n=n.next;
}
}
public int size(){
Node n=head;
int count=0;
while(n!=null){
count++;
n=n.next;
}
return count;
}
//插入节点
public void insert(Object object,int pos){
Node newNode=new Node(object);
int size=size();
if(pos<0||pos>size){
System.out.println("插入下标有误");
}
else if(pos==0){//表头插入
newNode.next=head;
head=newNode;
}
else if(pos>=size-1){//表尾插入,小标size()-1的next指向新节点,新节点next置为null
getNodeByPos(size-1).next=newNode;
}
else{//在中间位置插入
newNode.next=getNodeByPos(pos);
getNodeByPos(pos-1).next=newNode;
}

}
public Node getNodeByPos(int pos){
Node n=head;
if(pos<0||pos>size()){
System.out.println("插入下标有误");
return null;
}
else if(pos==0){
return head;
}
else{
for(int i=0;i<pos;i++)
n=n.next;
return n;
}
}
public static void main(String[] args) {
MyList list=new MyList();
list.insert(100, 0);
list.insert(7, 1);
list.insert(4, 2);
list.insert(500, 0);
list.insert(23, 3);
list.insert(33, 1);
list.travel();

}
}


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