zoukankan      html  css  js  c++  java
  • Singly linked list algorithm implemented by Java

    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
    
  • 相关阅读:
    mybatis中的配置文件的约束
    win10下PHP开发环境搭建
    装饰器的理解
    在iis上添加woff字体文件读取
    转发:使用sql命令查询视图中所有引用的基础表
    转:C4项目中验证用户登录一个特性就搞定
    转载:NSobject官方介绍
    thinkphp生命周期
    array_intersect_assoc — 带索引检查计算数组的交集
    array_flip — 交换数组中的键和值
  • 原文地址:https://www.cnblogs.com/Alandre/p/4102848.html
Copyright © 2011-2022 走看看