码迷,mamicode.com
首页 > 编程语言 > 详细

Java数据结构系类之——链表(2):单向循环链表及相关常用操作

时间:2014-11-22 09:17:42      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:io   ar   java   for   数据   on   ad   amp   as   

package LinkList.onewaycircular;

public class Node {
	public int data;
	public Node next;
	
	//头结点初始化
	public Node(Node next){
		this.next=next;
	}
	
	//一般结点初始化
	public Node(int data,Node next){
		this.data=data;
		this.next=next;
	}
}

********************************我华丽的割割*******************************************************************************

package LinkList.onewaycircular;

public class OnewayCircularLinkList {
	Node head;//头结点
	Node current;//当前结点
	int size;//链表大小
	
	//初始化空链表
	public OnewayCircularLinkList(){
		this.head=new Node(null);
		this.current=this.head;
		size=0;
		this.current.next=this.head;
	}
	// 判断线性表是否为空
	public boolean isEmpty(){
		return size==0;
	}
	
	// 获取指定位置的元素,这里我们定义头结点head的index为-1
	public Node getElement(int index){
		if(index<-1||index>=size){
			throw new RuntimeException("参数错误");
		}
			
		if(index==-1){
			current=head;
		}else{
			current=head.next;
		}
		
		for(int i=0;i<index&¤t.next!=head;i++){
			current=current.next ;
		}
		
		return current;
	}
	
	// 在指定位置插入元素,这里我们定义头结点head的index为-1
	public void insert(int index , int data){
		Node node=new Node(data,null);
		
		Node prev=getElement(index-1);//当前结点的前一个结点
		
		node.next=prev.next;
		prev.next=node;
		
		size++;
	}
	
	// 删除指定位置的元素
	public void delete(int index){
		if(index>size-1){
			throw new RuntimeException("参数错误");
		}
		Node prev=getElement(index-1);//当前结点的前一个结点
		
		current=prev.next;
		prev.next=current.next;
		current.next=null;
		size--;
	}
	
	//打印链表
	public void traverse(){
		if(isEmpty()){
			System.out.println("null");
		}else{
			current=head.next;
			while(current!=head){
				System.out.print(current.data+" ");
				current=current.next;
			}
			System.out.println();
		}
	}
}


Java数据结构系类之——链表(2):单向循环链表及相关常用操作

标签:io   ar   java   for   数据   on   ad   amp   as   

原文地址:http://blog.csdn.net/tmwl0728/article/details/41372823

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!