Java 链表实现

先定义节点:

package CareerCup;

public class Node
{
	public Node next = null;
	public int data = 0;
	
	public Node(){}
	
	public Node(int data)
	{
		this.data = data;
		this.next = null;
	}
	
	public void setData(int data)
	{
		this.data = data;
	}	
}

再定义链表结构:

package CareerCup;

public class LinkedList 
{
	public Node header = null;
	public Node tail = null;
	
	public LinkedList(){}
	
	public void add(int data)
	{
		if(header == null)
		{
			Node node = new Node(data);
			header = node;
			tail = node;
		}
		else
		{
			Node node = new Node(data);
			tail.next = node;
			tail = node;
		}
	}
	
	public int getData(int index)
	{
		Node temp = header;
		for(int i=0;i<index;i++)
			temp = temp.next;
		return temp.data;
	}
	
	public void deleteHead()
	{
		header = header.next;
	}
	
	public void deleteTail()
	{
		Node temp = header;
		while(temp.next!=tail)
			temp = temp.next;
		tail = temp;
		tail.next = null;
	}
	
	public void deleteData(int data)
	{
		if(header.data == data) header = header.next;
		Node pre = header;
		Node temp = pre.next;
		while(temp.next!=null)
		{
			if(temp.data!=data)
			{
				pre = temp;
				temp = temp.next;
			}
			else
			{
				pre.next = temp.next;
				temp = temp.next;
			}
		}
		if(tail.data==data)
		{
			temp.next = null;
			tail = temp;
		}
	}
	
	public void deleteIndex(int index)
	{
		Node pre = header;
		Node temp = header;
		for(int i=0;i<index;i++)
		{
			pre = temp;
			temp = temp.next;
		}

		pre.next = temp.next;
	}
	
	public void print()
	{
		Node temp = this.header;
		while(temp.next!=null)
		{
			System.out.print(temp.data+"->");
			temp = temp.next;
		}
		System.out.print(tail.data);
		System.out.println();
	}
      public void creatLoop(int[] data)
	{
		HashMap
  
  
   
    posMap = new HashMap
   
   
    
    ();
		for(int i=0;i<data.length;i++)
		{
			int item = data[i];
			if(!posMap.containsKey(item))
			{
				this.add(item);
				posMap.put(item, i);
			}
			else
			{
				int pos = posMap.get(item);
				Node node = this.getNode(pos+1);
				this.addNode(node);
			}
		}
	}
}
   
   
  
  


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值