数据结构—线性表的存储方式
线性表的存储方式有两种,一种是顺序表,另外一种是链表。顺序表是一种简单且常用的存储方式。在顺序表中,逻辑相邻的数据,存储地址也相邻。在链表中,逻辑相邻的数据,存储地址不一定相邻。
顺序表的实现比较简单,通常用数组实现,数组长度确定,将逻辑相邻的数据存储在相邻的地址中,可以计算每个数据的地址,由序号快速查找数据。但是插入、删除需要平均移动
O(n)数据,很不方便。在长度为n的线性表中第i个位置插入数据的过程,需要移动n-i个数据,删除第i个位置的数据需要移动n-i-1个数据。线性表的顺序表代码实现如下:
public class linearDeno1{ private int currentLength; private int array[]=new int[100]; public linearDemo1{ array[]=new int[100];}public void add(int temp){array[current]=temp;currentLength++;}public void insert(int i,int temp){int j;for( j=currentLength-1;j>i-1;j--){array[j+1]=array[j];}array[j]=temp;}public void deleteNum(int i){for( j=currentLength-1;j>i-1;j--){array[j-1]=array[j];}public void deleteContent(int temp){for(int i=0;i<currentLength;i++){if(array[i]==temp)}{for(int j=j=currentLength-1;j>i-1;j--){array[j-1]=array[j];}}}}}
public class Node{private int name;private Node next;public Node(){}public Node(int name){this.name=name;}public Node(Node next){this.next=next;}public Node(int name,Node next){this.name=name;this.next=next;}public void setName(){this.name=name;}public int getName(){return name;}public void setNext(){this.next=next;}public int getNext(){return next;}}public class linearDeno2{private Node head;public linearDeno2{head =new Node(5);}public void initFirst(Node temp){temp.setNext(head.getNext);head.setNext(temp);}public void initLast(Node temp){int length = getLength();insert(length,temp);}public void insert(int i,Node temp){Node p=getNode(i-1);temp.setNext(p.getNext());p.setNext(temp);}public void delete(int i){Node p=getNode(i-1);p.setNext(p.getNext.getNext)}public void delete(Node temp){int i=0;Node p=head.getNext();while(p!=null){if(p.getNext().equals(temp){Node p=getNode(i-1);p.setNext(p.getNext.getNext})}public int getLength(){int length=0;if(head.getNext()!=null){Node p=head.getNext();while(p!=null){p=p.getNext}length++;}return length;}public Node getNode(int i){if(i<0||i>getLength()){throw new Exception("输入不合法!");}int j=0;Node p=head.getNext();while(p!=null&&j<i){p=p.getNext();j++;}return p; }}