日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

链表的基本操作 java_JAVA实现单链表的基本操作

發(fā)布時間:2024/10/12 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 链表的基本操作 java_JAVA实现单链表的基本操作 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

復(fù)習(xí)單鏈表的實現(xiàn),扎實基礎(chǔ),單鏈表的結(jié)構(gòu)不在贅述,直接看代碼,注釋的很清楚

注意:在插入和刪除操作時,需要判斷是否越界,如何判斷上界?想到了在修改.

public class linkList {

//定義一個節(jié)點類,存儲數(shù)據(jù)和引用

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);//使用傳入的參數(shù)實例化一個節(jié)點

if(head==null){

head=newnode;

return;

}

Node temp=head;//一個移動的指針(把頭結(jié)點看做一個指向結(jié)點的指針)

while(temp.next!=null){//遍歷單鏈表,直到遍歷到最后一個則跳出循環(huán)。

temp=temp.next;//往后移一個結(jié)點,指向下一個結(jié)點。目的是找到最后一個結(jié)點

}

temp.next=newnode;//temp為最后一個結(jié)點或者是頭結(jié)點,將其next指向新結(jié)點

}

//在index位置后面插入位置插入指定元素結(jié)點

public void insertnodebyindex(int index,int i){

//判斷插入位置合法性(下界和上界,如何獲得上界)

if(index<1){

System.out.println("不合法");

return;

}

int length=0;//記錄遍歷的位置

//創(chuàng)建包含要插入元素的結(jié)點

Node node=new Node(i);

//移動的指針

Node temp=head;

while(temp.next!=null){

//從第一個元素開始找

length++;

if(index==length){

//1.temp的后繼結(jié)點改成為新插入結(jié)點的后繼結(jié)點

node.next=temp.next;

//2.在把新插入的結(jié)點變成p的后繼結(jié)點

temp.next=node;

return;

}

//沒找到index時向后循環(huán)遍歷鏈表

temp=temp.next;

}

}

//刪除index后一個位置的結(jié)點

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的后繼結(jié)點改成temp的后繼結(jié)點的后繼結(jié)點

//即讓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;

}

//打印結(jié)點

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());

}

}

總結(jié)

以上是生活随笔為你收集整理的链表的基本操作 java_JAVA实现单链表的基本操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。