java链表的实现

结点类

package linkList;


//结点类
public class Node { 
	protected Node next; //指针域
	protected int data; //数据域
	
	public Node(int data){
		this.data=data;
	}
	
	public void display(){
		System.out.println(data + " ");
	}	

}

链表实现

package linkList;

public class Mylist {
	
	public Node head; //定义一个头结点
	public Node current; //当前结点
	
	//添加元素
	public void add(int data){
		//判断链表是否为空 
		if(head==null)   //如果头结点为空,说明这个链表还没有被创建
		{
			head = new Node(data);
			current = head;
		}else  
		{
			//创建新的结点
			Node node = new Node(data);
			//放在当前结点的后面
			current.next=node;
			//把链表的当前索引向后移动一位
			current=current.next;		
			
		}		
	}
	
	//获取单链表的长度
	public int getLength()
	{
		//头结点为空则返回0
		if(head==null)
			return 0;
		else
		{
			int length=0;
			Node current = head;
			while(current!=null)
			{
				current=current.next;
				length++;
			}
			return length;
		}
	}
	
	
	//打印链表
	public void printList(){
		Node tmp = head;
		while(tmp!=null)
		{
			System.out.println(tmp.data+" ");
			tmp=tmp.next;
		}
	}
	
	
	//删除第index个结点
	public boolean deleteNode(int index){
		if(index<1||index>this.getLength())
			return false;
		if(index==1){
			head=head.next;
			return true;
		}
		int i =1;
		Node proNode = head;
		Node curNode = proNode.next;
		while(curNode!=null)
		{
			if(i==index)
			{
				proNode.next=curNode.next;
				return true;
			}
			proNode = curNode;
			curNode = curNode.next;
			i++;
		}
		return false;
	}
	

 
	//链表反转 遍历实现
	public static Node Reverse(Node head)
	{
		if(head==null||head.next==null)
			return head;
		Node pre=head; //上一结点
		Node cur=head.next; //当前结点
		Node tmp ;//临时结点,用于保存当前指针域
		while(cur!=null)
		{
			tmp=cur.next;
			
			cur.next=pre;  //反转指向
			
			//指针向下移动
			pre=cur;			
			cur=tmp;
		}
		head.next=null ;//将头结点设空
		
		return pre;
		
		
	}
	
	//判断单链表是否有环,我们用两个指针去遍历:
	//first指针每次走一步,second指针每次走两步,如果first指针和second指针相遇,说明有环。
	
	     public boolean hasCycle(Node head) {
 
		       if (head == null) {
	            return false;
	         }
	 
	          Node first = head;
	        Node second = head;
		  
		        while (second != null) {
	             first = first.next;   //first指针走一步
          second = second.next.next;  //second指针走两步
	 
	             if (first == second) {  //一旦两个指针相遇,说明链表是有环的
	                 return true;
	             }
       }
		 
	          return false;
		     }
 
	
	public static void main(String[] args) {		
		
		  Mylist list = new Mylist();
		  list.add(1);
		  list.add(2);
		  list.add(3);
		  list.add(1);
		  list.printList();
		  
		  System.out.println(list.hasCycle(list.head)); 
		  
		  
	 	
		
	}
	

	
}

参考博客 https://www.cnblogs.com/smyhvae/p/4782595.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值