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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

链表的基本操作 java_Java-实现链表的基本操作

發布時間:2024/9/3 java 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 链表的基本操作 java_Java-实现链表的基本操作 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Node.java

package com.wanali.java_ds.linklist;

//節點類

public class Node {

public Object data;

public Node next;

// 無參的構造函數

public Node() {

this.data = null;

this.next = null;

}

// 一個參數的構造函數

public Node(Object data) {

this.data = data;

this.next = null;

}

// 兩個參數的構造函數

public Node(Object data, Node next) {

this.data = data;

this.next = next;

}

}

LinkList.java

package com.wanali.java_ds.linklist;

//鏈表類

public class LinkList {

public Node head;

public LinkList next;

// 初始化頭結點

public LinkList() {

head = new Node();

}

public void creat(int i, Object x) {

Node p = new Node(x);// 實例化一個節點

Node pNode = head;

while (pNode != null)

pNode = pNode.next;

pNode.next = p;

}

public void display() {

Node pNode = head.next;

while (pNode != null) {

System.out.println(pNode.data);

pNode = pNode.next;

}

}

// 插入

public void insert(int i, Object x) throws Exception {

Node pNode = head;

int j = 0;//

while (pNode != null && j < i - 1) {

pNode = pNode.next;

++j;

}

if (j > i - 1 || pNode == null)

throw new Exception("插入的位置不合法");

Node t = new Node(x);

t.next = pNode.next;

pNode.next = t;

}

public void delete(int i) {

Node pNode = head;

if (i < 1)

System.out.println("輸入的值不正確!!!");

while (pNode.next != null && --i > 0) {

pNode = pNode.next;

}

Node delnode = pNode.next;

pNode.next = delnode.next;

}

public Object get(int i) {

Node pNode = head;

int j = 0;

while (pNode != null && j != i) {

pNode = pNode.next;

j++;

}

return pNode.data;

}

public Object length() {

Node pNode = head;

int j = 0;

while (pNode != null) {

pNode = pNode.next;

j++;

}

return j;

}

}

TestLinkList.java

package com.wanali.java_ds.linklist;

public class TestLinkList {

public static void main(String[] args) {

LinkList linkList = new LinkList();

try {

linkList.creat(1, 10);

linkList.creat(2, 20);

linkList.creat(3, 30);

System.out.println("打印鏈表中的元素:");

linkList.display();

System.out.println("在第2個位置插入元素:");

linkList.insert(2, 0);

linkList.display();

System.out.println("插入的元素為:" + linkList.get(2));

System.out.println("刪除第3個元素:");

linkList.delete(3);

linkList.display();

System.out.println("鏈表長度為:" + "\n" + linkList.length());

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

運行結果如下:

總結

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

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。