巩固链表创建、查找、插入、删除等基本操作,复习巩固Java语法知识。
import java.util.*;
public class Test20
{
public static void main(String[] args)
{
Scanner In=new Scanner(System.in);
int n=In.nextInt();
Node head=null;
head=creat(n);
search1(head,2,n); //依据所给位置:查询第二个元素的值;
search2(head,5); //依据所给数值:查找前、后驱节点,此步查询3的节点;
head=Insert(head,4,99); //在第四个节点后插入新节点,并赋值为99;
head=delete(head,3,n); //删除第3个节点;
print(head);
}
public static Node creat(int n){ //创建
Node p=null;
Node head=null;
for(int i=0;i<n;i++){ //尾插法
Node newnode=new Node(i); //初始化链表数据
if(head==null){
head=newnode;
p=head;}
else{
p.next=newnode;
newnode.next=null;
p=newnode;}
}
return head;
}
public static void search1(Node head,int x,int n){ //依据所给位置查找
Node p=head;
if(x<1||x>n){
System.out.println("error");
return ;}
else{
for(int i=0;i<x-1;i++){
p=p.next;}
System.out.println(p.date);
}
}
public static void search2(Node head,int m){
Node p=head;
Node pre=head;
if(head==null||head.next==null){
System.out.println("error"); //当链表为空或者只有一个头节点时,无前后驱节点;
return ;}
else{
while(p!=null){
if(p.date!=m){
p=p.next;}
if(pre.next.next==p){
pre=pre.next;} //pre移动判定,保证pre在p之前
if(p.date==m||p==null){ //不加这个条件就可能挑不出循环,当p.date==m时,p不移动,死循环!
break;}
}
if(p==head){
System.out.printf("无前驱节点,后驱节点为%d\n",p.next.date);}
else if(p.next==null){
System.out.printf("无后驱节点,前驱节点为%d\n",pre.date);}
else{
System.out.printf("前驱节点为%d,后驱节点为%d\n",pre.date,p.next.date);}
}
}
public static Node Insert(Node head,int y,int e){ //插入
Node newnode=new Node(e);
Node p=head;
Node q=head.next;
for(int i=0;i<y-1;i++){
p=p.next;
q=q.next;}
p.next=newnode;
newnode.next=q;
return head;
}
public static Node delete(Node head,int z,int n){ //删除
if(z<1||z>n){
System.out.println("error");
return head;}
else{
Node p=head.next;
Node q=p.next;
Node pre=head;
if(z==1){
head=head.next;
return head;}
else{
for(int i=0;i<z-2;i++){
p=p.next; //删除p所在的位置;
q=p.next;
pre=pre.next;}
pre.next=q;
}
}
return head;
}
public static void print(Node head){
Node p=head;
while(p!=null){
System.out.printf("%d ",p.date);
p=p.next;}
System.out.println();
}
}
class Node
{
public Node(int date){
this.date=date;
}
int date;
Node next;
}
在标记当前元素的前一个节点时,一个while循环实现标记并查找。
通过本次Java实现,再一次巩固了Java语法,熟悉了链表的各种操作,也算是一种进步吧,希望以后再接再厉吧!
原文:https://www.cnblogs.com/DongChenYi/p/11715375.html