学习内容:
链表基础
重点归纳:
见例题
例题:
解:
点击查看代码
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();
}
}