package com;
import java.util.Scanner;
/**
* @Author: LC
* @Date: 2022/3/11 19:37
a001链表基础
*/
public class a001单链表基础 {
// 成员类 代表节点
// 节点类 有两个属性 一个 数据 一个 指针
static class Node{
// 数据
int data;
// 指向下一个的指针
Node next;
// 构造方法 用于给数据 赋值
Node(int v){
data=v;
}
}
//头结点单独列出来
static Node head=new Node(1);
//初始化
static void init(){
// 创建一个临时变量 默认指向头节点
Node x=head;
//建立单项列表
for (int i = 1; i <=10 ; i++) {
x=(x.next=new Node(i));
}
// 最后末尾的节点 指向空地址
x.next=null;
}
//删除功能
static void del(int x){
//用于存放当前节点的前驱
//因为单链表单向遍历,我们不能从下一个找到上一个
Node Befor=head;
// 链表的遍历 常用写法
for (Node T = head.next; T !=null ; T=T.next) {
// 找到要找到的那个值了
if (T.data==x){
// 临时保存节点
Node temp=T;
// 将节点从链表上删除
Befor.next=T.next;
// 删除节点后 结束函数
return;
}
Befor=T;
}
}
// 插入功能
static void insert(int x){
Node temp=new Node(x);
temp.next=head.next;
head.next=temp;
}
// 显示功能
static void show(int i){
// 链表的遍历 常用写法
for (Node T = head.next; T!=null ;T=T.next) {
System.out.println(T.data+" ");
}
System.out.println(" ");
}
public static void main(String[] args) {
int N;
Scanner sc=new Scanner(System.in);
init();
N=sc.nextInt();
for (int i = 0; i <N ; i++) {
int x=sc.nextInt();
// 测试删除节点
del(x);
//测试插入节点
insert(x);
//遍历节点
show(i);
}
}
}