链表的基本操作 java_JAVA实现单链表的基本操作
復習單鏈表的實現,扎實基礎,單鏈表的結構不在贅述,直接看代碼,注釋的很清楚
注意:在插入和刪除操作時,需要判斷是否越界,如何判斷上界?想到了在修改.
public class linkList {
//定義一個節點類,存儲數據和引用
class Node{
private int data;
private Node next=null;
public Node(int data) {
super();
this.data = data;
}
}
Node head=null;//鏈表頭的引用初始化為空
//尾插
public void addNode(int a) {
Node newnode=new Node(a);//使用傳入的參數實例化一個節點
if(head==null){
head=newnode;
return;
}
Node temp=head;//一個移動的指針(把頭結點看做一個指向結點的指針)
while(temp.next!=null){//遍歷單鏈表,直到遍歷到最后一個則跳出循環。
temp=temp.next;//往后移一個結點,指向下一個結點。目的是找到最后一個結點
}
temp.next=newnode;//temp為最后一個結點或者是頭結點,將其next指向新結點
}
//在index位置后面插入位置插入指定元素結點
public void insertnodebyindex(int index,int i){
//判斷插入位置合法性(下界和上界,如何獲得上界)
if(index<1){
System.out.println("不合法");
return;
}
int length=0;//記錄遍歷的位置
//創建包含要插入元素的結點
Node node=new Node(i);
//移動的指針
Node temp=head;
while(temp.next!=null){
//從第一個元素開始找
length++;
if(index==length){
//1.temp的后繼結點改成為新插入結點的后繼結點
node.next=temp.next;
//2.在把新插入的結點變成p的后繼結點
temp.next=node;
return;
}
//沒找到index時向后循環遍歷鏈表
temp=temp.next;
}
}
//刪除index后一個位置的結點
public void deleteNode(int index){
if(index<1){
System.out.println("不合法");
return;
}
Node temp=head;
int length=0;
while(temp.next!=null){
length++;
if(index==length){
//把temp的后繼結點改成temp的后繼結點的后繼結點
//即讓temp的指針域指向temp的后面的后面的元素
temp.next=temp.next.next;
return;
}
temp=temp.next;
}
}
//獲取鏈表長度
public int size(){
int length=1;
Node temp=head;
while(temp.next!=null){
length++;
temp=temp.next;
}
return length;
}
//打印結點
public void printlist(){
Node temp=head;
while(temp!=null){
System.out.print(temp.data);
temp=temp.next;
}
}
public static void main(String[] args) {
linkList list=new linkList();
list.addNode(2);
list.addNode(3);
list.addNode(4);
list.addNode(5);
list.addNode(8);
list.addNode(0);
list.addNode(6);
list.printlist();
System.out.println("\t");
//Node insertnode=new Node(0);
//在3號元素后面插入
list.insertnodebyindex(3 ,9);
list.printlist();
System.out.println("\t");
//刪除
list.deleteNode(3);
list.printlist();
System.out.println("\t");
System.out.println(list.size());
}
}
總結
以上是生活随笔為你收集整理的链表的基本操作 java_JAVA实现单链表的基本操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java.util 找不到_java.u
- 下一篇: java multivaluemap_j