卡码java基础课 | 13.链表的基础操作I

学习内容:
链表基础

重点归纳:
见例题

例题:


解:

点击查看代码
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 data){
        Node newNode = new Node(data);
        this.length++;
        if(this.headNode == null){
            this.headNode = newNode;
            return this.headNode;
        }
        else{
            Node currentNode = this.headNode;
            while(currentNode.next != null){
                currentNode = currentNode.next;
            }
            currentNode.next = newNode;
            return newNode;
        }

    }
    
    //打印数据
    public void printLinkedList(){
        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);
        
        while(sc.hasNext()){
            int n = sc.nextInt();
            LinkedList newLinkList = new LinkedList();
            for(int i = 0; i < n; i++){
                newLinkList.Insert(sc.nextInt());
            }
            newLinkList.printLinkedList();
        }
        
        sc.close();
    }
    
}


posted @   小陈-自学记录  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示