单链表的简单实现

<span style="font-size:14px;">import java.util.Scanner;
class node
{
	int data;
	node next;
	public node(int x)
	{
		this.data=x;
		this.next=null;
	}
	public node retnode()
	{
		return this;
	}
}
class LinkList
{
	 node head;
	 public LinkList()
	 {
		 head=new node(-1);
		 //头结点为-1,意为头结点为空指针
	 }
	public void insert(int value)
	{//为value创建一个结点,并且插入链表中
		node nd=new node(value);
		if(head.next==null)
			head.next=nd.retnode();
		else 
		{
			node tmp=head.next;
			while(tmp.next!=null)
				tmp=tmp.next;
			tmp.next=nd.retnode();
		}
	}
	public void Print()
	{//打印链表
		node tmp=head.next;
		while(tmp!=null)
		{
			System.out.print(tmp.data+" ");
			tmp=tmp.next;
		}
	}
	public boolean findx(node l,int value)
	{//查找值为value的结点,如能找到返回true,否则返回false
		if(l==null) return false;
		if(l.data==value) return true;
		return findx(l.next,value);
	}
	public void deleNode(node pre,node nd,int value)
	{//删除值为value的结点
		if(nd==null)
		{
			System.out.println("The number "+value+" doesn't exit!!!");
			return;
		}
		if(nd.data==value)
		{
			pre.next=nd.next;
			return;
		}
		deleNode(nd,nd.next,value);
	}
}
public class Main
{
	public static void main(String[] args)
	{
		Scanner in=new Scanner(System.in);
		while(in.hasNext())
		{
			LinkList LL=new LinkList();
			int n=in.nextInt();
			for(int i=1;i<=n;i++)
			{
				int x=in.nextInt();
				LL.insert(x);
			}
			LL.Print();
			System.out.println();
			System.out.println(LL.findx(LL.head.next,7));
			LL.deleNode(LL.head, LL.head.next, 5);
			LL.Print();
			System.out.println();
			LL.deleNode(LL.head, LL.head.next, 11);
			LL.Print();
			System.out.println();
		}
	}
}</span>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值