[数据结构]java实现的简单链表的 头/尾插法

链表的图解

尾插法:

package structure;


import java.io.*;
import java.util.*;

class Node {
    int data;
    Node next;
    Node(int d) {
        data = d;
        next = null;
    }
}
public class Test3 {



    public static  Node insert(Node head,int data) {

        Node n=new Node(data);

        //尾插法先要确定头结点是否为空,空的话先将第一个结点给头结点
        Node p=head;
        if(head==null){
            n.next=head;
            head=n;
        }else{
            while(p.next!=null){
                p=p.next;//p结点始终指向最后一个结点
            }

            p.next=n;//在尾部插入新结点
        }

        return head;
    }
    public static void display(Node head) {
        //打印链表的data
        Node start = head;
        while(start != null) {
            System.out.print(start.data + " ");
            start = start.next;
        }
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        Node head = null;
        int N = sc.nextInt(); //输入链表的长度

        while(N-- > 0) {           //逐个输入链表元素
            int ele = sc.nextInt();
            head = insert(head,ele);
        }
        display(head);
        sc.close();
    }
}

头插法

 package structure;


import java.io.*;
import java.util.*;

class Node {
    int data;
    Node next;
    Node(int d) {
        data = d;
        next = null;
    }
}
public class Test3 {

    public static  Node insert(Node head,int data) {

        Node n=new Node(data);
        n.next=head;
        head=n;
        return head;
    }
    public static void display(Node head) {
        //打印链表的data
        Node start = head;
        while(start != null) {
            System.out.print(start.data + " ");
            start = start.next;
        }
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        Node head = null;
        int N = sc.nextInt(); //输入链表的长度

        while(N-- > 0) {           //逐个输入链表元素
            int ele = sc.nextInt();
            head = insert(head,ele);
        }
        display(head);
        sc.close();
    }
}

后续数据结构上的java构造链表还会翻新的,以数据结构而分类的文章们,纯粹是为了复习准备考研而写的几篇文章

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值