啥也不多少,原理都一樣,只是實現的方式不一樣而已,原理介紹請自行百度百科百科百科-單鏈表
分析:
數據的內容我們這邊將存儲整型 定義一個int 型的data
對於Java 下一個節點的引用類型就是該節點自己,即可將類定義如下:
public class Node{
Node next = null;
int data
}
public class MyList{
Node head = null;
public class Node {
Node next = null
int data ;
}
// 增加節點 從尾部開始插入
public void addNode(int data){
// 首先判斷該鏈表是否存在元素
Node newNode = new Node();
if(head == null )// 沒有元素
{
node.head = newNode;
}
else{
// 鏈表中存在節點,遍歷找到最後的節點(尾部插入)
Node tmp = head;//不修改頭節點地址
while(tmp.next != null )
tmp = tmp.next
}
//找到尾部節點next爲null ,將該節點地址賦值在最後一個節點next位置
tmp.next = newNode ;
}
//刪除節點 傳入索引值
public boolean deleteNode(int index){
// 首先判斷待刪除的節點是否存在
if(index > length || index < 0)
return -1;
if (index == 1) {
head = head.next;
return true;
}
int i = 1;
Node preNode = head;
Node curNode = preNode.next;
while (curNode != null) {
if (i == index) {
preNode.next = curNode.next;
return true;
}
preNode = curNode;
curNode = curNode.next;
i++;
}
return false;
}
public int length(){
int i = 0;
Node tmp = head;
if(head == null) return 0;
while(tmp.next != null)
{
tmp = tmp.next;
i++;
}
return i;
}
}