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; }