卡码java基础课 | 15.链表的基础操作III
学习内容:
面向对象的方法重载;Java自带的双向链表LinkedList。
重点归纳:
方法的重载:方法名称相同,但参数不同,比如参数个数、参数类型或参数顺序不同,返回类型可以相同也可以不相同。
LinkedList:本质是双向链表结构,定义和声明举例LinkedList
例题:
解:
点击查看代码
import java.util.Scanner;
//定义链表
class LinkedList{
//定义链表中的链表节点
public static class Node{
int data; //数据
Node next; //指针
public Node(int data){ //构造函数
this.data = data;
this.next = null;
}
}
private Node headNode; //头节点
private int length; //链表长度
public LinkedList(){ //链表的构造函数
this.length = 0;
this.headNode = null;
}
//插入数据函数
public Node Insert(int location, int data){
Node newNode = new Node(data);
if(location > (this.length + 1) || location <= 0){
System.out.println("Insertion position is invalid.");
return null;
}
else{
this.length++;
if(this.headNode == null){
this.headNode = newNode;
}
else{
if(location == 1){
newNode.next = this.headNode;
this.headNode = newNode;
}
else{
Node currentNode = this.headNode;
for(int i = 0; i < (location - 2); i++){
currentNode = currentNode.next;
}
newNode.next = currentNode.next;
currentNode.next = newNode;
}
}
return newNode;
}
}
//删除数据
public Node Delete(int location){
if(location <= 0 || location > this.length){
System.out.println("Deletion position is invalid.");
return null;
}
else{
this.length--;
if(location == 1){
if(this.length == 0){
this.headNode = null;
return null;
}
else{
this.headNode = this.headNode.next;
return this.headNode;
}
}
else{
Node currentNode = this.headNode;
for(int i = 0; i < location - 2; i++){
currentNode = currentNode.next;
}
currentNode.next = currentNode.next.next;
return currentNode;
}
}
}
public int getLength(){
return this.length;
}
//打印数据
public void printLinkedList(){
if(this.length != 0){
Node currentNode = this.headNode;
while(currentNode != null){
System.out.print(currentNode.data + " ");
currentNode = currentNode.next;
}
System.out.println();
}
}
}
public class Main{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
LinkedList newLinkList = new LinkedList();
for(int i = 0; i < k; i++){
int len = newLinkList.getLength();
int num = sc.nextInt();
newLinkList.Insert(len + 1, num);
}
int S = sc.nextInt();
for(int i = 0; i < S; i++){
int n = sc.nextInt();
int x = sc.nextInt();
if(newLinkList.Insert(n, x) != null){
newLinkList.printLinkedList();
}
}
int L = sc.nextInt();
for(int i = 0; i < L; i++){
int loc = sc.nextInt();
if(newLinkList.Delete(loc) != null){
newLinkList.printLinkedList();
}
}
sc.close();
}
}
分类:
java学习-卡玛网课程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~