Singly linked list algorithm implemented by Java

本文详细介绍了链表这一基本数据结构的实现方法,并通过具体的代码示例展示了如何创建链表节点,实现添加、插入、删除节点等核心操作。此外,还提供了一个测试类来验证链表操作的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Jeff Lee blog:   http://www.cnblogs.com/Alandre/  (泥沙砖瓦浆木匠),retain the url when reproduced ! Thanks

 

Linked list is a normal data structure.here I show how to implements it.

Step 1. Define a structure

public class ListNode
{
	public ListNode Next;
	public int Value;
	public ListNode(int NewValue)
	{
		Value = NewValue;
	}
}

Step 2. implements the functions

public class Clist
{
	private ListNode Head;
	private ListNode Tail;
	private ListNode Current;
	private int ListCountValue;
	
	public Clist()
	{
		ListCountValue = 0;
		Head = null;
		Tail = null;
	}
	
	public void Append(int DataValue)
	{
		ListNode NewNode = new ListNode(DataValue);
		if (ListCountValue == 0)
		{
			Head = NewNode;
			Tail = NewNode;
		}
		else
		{
			Tail.Next = NewNode;
			Tail = NewNode;
		}
		Current = NewNode;
		ListCountValue += 1;
	}
	
	public void Insert(int DataValue)
	{
		ListNode NewNode = new ListNode(DataValue);
		if (ListCountValue == 0)
		{
			Append(DataValue);
			return;
		}
		if(Current == Tail)
		{
			Tail.Next = NewNode;
			Tail = NewNode;
			Current = Tail;
			ListCountValue += 1;
		}
		if((Current != Head) && (Current != Tail))
		{
			NewNode.Next = Current.Next;
			Current.Next = NewNode;
			Current = NewNode;
			ListCountValue += 1;
		}
	}
	
	public void Delete()
	{
		if(ListCountValue != 0)
		{
			if(Current == Head)
			{
				Head = Current.Next;
				Current = Head;
				ListCountValue -= 1;
				return;
			}
			else
			{
				Current = Current.Next;
				ListCountValue -= 1;
			}
		}
	}
	
	public void printAllListNode()
	{
		Current = Head;
		for (int i = 0; i < ListCountValue; i++)
		{
			System.out.println(Current.Value);
			Current = Current.Next;
		}
	}
}

Step 3. Test class for testing

public class Test
{

	public static void main(String[] args)
	{
		Clist clist = new Clist();
		clist.Append(12);
		clist.Append(22);
		clist.Insert(66);
		clist.Insert(33);
		clist.Delete();
		clist.printAllListNode();
	}

}

 

we will see:

12
22
66
33
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值