package algorithrm;
public class LinkList<T>{
private Node head;
private int N;
public class Node<T>{
public T val;
public Node next;
public Node(T val, Node next) {
this.val = val;
this.next = next;
}
}
//初始化
public LinkList(){
this.head = new Node(null, null);
this.N=0;
}
// 獲取頭結點
public Node gethead()
{
return this.head;
}
public void clear()
{
this.head=null;
this.N=0;
}
// 鏈表長度
public int length()
{
return this.N;
}
public T get(int i)
{
Node n = head.next;
for(int index=0;index<i;index++)
{
n=n.next;
}
return (T) n.val;
}
public void insert(T t)
{
Node n = head;
while(n.next!=null)
{
n=n.next;
}
Node newnode = new Node(t,null);
n.next =newnode;
this.N++;
}
public void inserttotail(T t)
{
Node<T> tNode = new Node<>(t, null);
tNode.next = head.next;
head.next=tNode;
this.N++;
}
public void insert(T t,int i)
{
//i位置前一個節點
Node pre = head;
for(int index =0;index<=i-1;index++)
{
pre=pre.next;
}
// 創建新節點
Node newnode = new Node(t,pre.next);
pre.next=newnode;
// 元素加1
this.N++;
}
public T remove(int i)
{
Node pre = head;
for(int index =0;index<=i-1;index++)
{
pre=pre.next;
}
// i位置的節點
Node curr = pre.next;
Node newnode = curr.next;
pre.next=newnode;
this.N--;
return (T)curr.val;
}
public int indexogf(T t)
{
Node n = head;
int i =0;
while(n.next!=null)
{
if(n.val==t)
return i;
n=n.next;
i++;
}
return -1;
}
}
java鏈表實現單鏈表常見操作
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.