码迷,mamicode.com
首页 > 其他好文 > 详细

手动实现单链表

时间:2016-03-11 22:23:04      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

???有点问题,再试试
单链表:
指针是指一个数据元素逻辑意义上的存储位置,链式存储机构是基于指针实现的,每一个节点由一个数据元素和一个指针构成。链式存储结构是用指针把相互关联的元素链接起来。
在单链表中,每个节点只有一个直接只想后继元素的指针,而双向链表中每个节点有两个指针,一个只想后继节点一个只想前驱节点。
单链表的实现
节点类:
package com.nishizhen.list;

public class Node {
Object element;
Node next;

Node(Node nextval){
next = nextval;
}

Node(Object obj,Node nextval){
element = obj;
next = nextval;
}

public Node getNext(){
return next;
}

public void setNext(Node nextval){
next = nextval;
}

public Object getElement(){
return element;
}

public void setElement(Object obj){
element = obj;
}

public String toString(){
return element.toString();
}
}
单链表类:
package com.nishizhen.list;

public class LinList implements List{
Node head;//头指针
Node current;//当前操作的节点位置
int size;//数据元素个数

LinList(){
head = current = new Node(null);
size = 0;
}

public void index(int i) throws Exception{
if(i<-1 || i>size-1){
throw new Exception("参数出错");
}
if(i==-1){
return;
}
current = head.next;
int j = 0;
while((current !=null)&&j<i){
current = current.next;
j++;
}
}

public void insert(int i,Object obj)throws Exception{
if(1<0 || i>=size){
throw new Exception("参数错误");
}

index(i-1);
current.setNext(new Node(obj,current.next));
size++;
}

public void delete(int i)throws Exception{
if(size==0){
throw new Exception("链表已空");
}
if(1<0 || i>=size){
throw new Exception("参数错误");
}

index

技术分享

(i-1);
Object obj = current.next.getElement();
current.setNext(current.next.next);

手动实现单链表

标签:

原文地址:http://www.cnblogs.com/fanguangdexiaoyuer/p/5267328.html

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