java 链表 头/尾插法

来源:互联网 发布:中国 英国 知乎 编辑:程序博客网 时间:2024/06/08 10:48

尾插法示意图
尾插法


import java.io.*;import java.util.*;class Node {    int data;    Node next;    Node(int d) {        data = d;        next = null;    }}public class Solution {    public static  Node insert(Node head,int data) {        //Complete this method        Node n=new Node(data);        //n.next=head;        //head=n;        //加上上面注释的两行,去掉以下的部分为“头插法”        //默认是尾插法        //尾插法先要确定头结点是否为空,空的话先将第一个结点给头结点        Node p=head;        if(head==null){            n.next=head;            head=n;        }else{            while(p.next!=null){                p=p.next;//p结点始终指向最后一个结点            }            n.next=p.next;//在尾部插入新结点            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();    }}
0 1