java 实现链表

                                                                                java 实现链表java

    在java中其实实现链表是一件极其简单的事情,就是对象的引用。示例代码以下:node

    //一个能够获取元素值,移除元素值地 链表结构。
    public  class Node {
	private Object item;
	public Node next;
	public Node(Object item,Node next) {
			this.item=item;
			this.next=next;
	}
	//获取元素
	public Object getItem(){
		return item;
	}
	//移除节点,没有考虑线程安全的简单数据结构
	public boolean removeNode(Node node){
		Node nod=this;
		int flag=0;
		while(nod!=null){
			if(nod.equals(node)){
				flag=1;
				break;
			}
			nod=nod.next;
		}
		if(flag==1&&nod.next!=null){
			if(nod.next.next!=null){
				nod.next=nod.next.next;
				
			}
			else{
				node.next=null;
			}
			return true;
		}
		return false;
	}
    }
    
    //使用方法
    public class TestMain {
	public static void main(String args[]){
		Node third=new Node(3,null);
		Node second=new Node(2,third);
		Node first=new Node(1,second);
		System.out.println(first.removeNode(third));//移除下一个是否成功
		Node node=first;
		while(node!=null){
			System.out.println(node.getItem());
			node=node.next;//遍历下一个
		}
	}
    }

    循环链表解决约瑟夫环问题:面试

    
    //循环链表
    public class Josephus {
	static	class Node{
		Node next;
		int val;
		Node(int val){
			this.val=val;
		}
	}
	
	public static void main(String args[]){
		int n=9;//多少人围成一个圈子
		int m=5;//第几我的出局
		Node t=new Node(1);
		Node x=t;
		for(int i=2;i<=n;i++){
			x=(x.next=new Node(i));//是一个移动的步骤
		}
		x.next=t;//保证是环路
		while(x!=x.next){//不是只剩一个的状况
			for(int i=1;i<m;i++){
				x=x.next;
			}
			x.next=x.next.next;
		}
		System.out.println(x.val);
	}
    }

    链表的反转(看似简单,谷歌面试来过的嘿嘿):安全

        //链表反转
	public static Node reverse(Node x){
		Node t,y=x,r=null;
		while(y!=null){
			t=y.next;//获取下一个指向对象
			y.next=r;//第一次会把把y转变成最后一个节点
			r=y;//不断加节点的过程
			y=t;//接着遍历下一个节点
		}
		return r;
	}
相关文章
相关标签/搜索