您的位置:首页 > 理论基础 > 数据结构算法

数据结构(一):顺序表

2015-01-07 11:17 92 查看
1. 线性表
分为顺序表和链表
顺序表用数组实现,插入和删除会引起大量元素的移动, 链表用包含Node内部类的LinkedList类实现, 用引用代替指针
public class SingleLinkedList<E> implements List<E>{

private Node head;
private int length = 0;

public SingleLinkedList(){
this.head = new Node(); //初始化头指针(data=null,prior=null)
}
@Override
public void clear() {
for(Node node = head.next;node != null;){
Node x = node.next;
node.data = null;
node.next = null;
node = x;
}
}

@Override
public int indexOf(E e) throws Exception {
if(length ==0)
throw new Exception("链表为空");
int index = 0;
Node n = head.next;
while(n!=null && n.data != e){
index++;
n = n.next;
}
if (n!=null)
return index;

return -1;
}

@Override
public void insert(int index, E e) throws Exception {
if (index>length)
throw new Exception("超出链表范围");
int j = 0;
for(Node n = head;n!=null;){
if(j!=index){
n = n.next;
j++;
}else{
Node newNode = new Node(e); //创建新节点
newNode.next = n.next;
n.next = newNode;
break;
}
}
length ++;
}

@SuppressWarnings("unchecked")
@Override
public E get(int index) {
if (index > length-1)
throw new RuntimeException("超出链表范围");
Node n = head.next;
for(int j=0;j<=length-1;j++){
if(j == index){
return (E)n.data;
}else{
n = n.next;
}
}
return null;
}

@Override
public boolean isEmpty() {
return head.next == null;
}

@Override
public int length() {
Node n = head.next;
int length = 0;
while(n != null){
n = n.next;
length ++;
}
return length;
}

@Override
public void remove(int index) throws Exception {
if (index>length-1)
throw new Exception("超出链表范围");
int j = 0;
for(Node n = head;n!=null;){
if(j!=index){
n = n.next;
j++;
}else{
Node node = n.next;
n.next = node.next;
node = null;
break;
}
}
length --;
}

@Override
public void show() {
Node n = head.next;
while(n != null){
System.out.print(n.data+",");
n = n.next;
}
System.out.println();
}

class Node{
private Object data;
private Node next;

public Node(){	// 用与初始化head指针
this.data = null;
this.next = null;
}

public Node(Object o){ //用于构造新节点
this.data = o;
this.next = null;
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public Node getNext() {
return next;
}

public void setNext(Node next) {
this.next = next;
}
}

public static void main(String[] args) throws Exception {
SingleLinkedList<Integer> ss = new SingleLinkedList<Integer>();
ss.insert(0, 1);
ss.insert(1, 2);
System.out.println(ss.length);
System.out.println(ss.get(1)+"sssssss");;
ss.remove(1);
ss.show();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: