尾插法:
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构造链表还会翻新的,以数据结构而分类的文章们,纯粹是为了复习准备考研而写的几篇文章