1.线性结构
数据结构里最简单最基础的一种数据结构,比如线性表
如何表示多项式?
方法一:顺序存储结构直接表示
那么有一个问题多项式为x+3x^2000时,如果还想上面这么表示,那么就要开辟a[2001],只有两项有系数,其他都浪费了。
方法二:顺序存储结构标识非零项
注意:此方法要按照i的幂次排序,运算才方便
这种方法,节省空间,而且运算效率也不算差
方法三:链表结构存储非零项
java中如何定义链表
class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data=data;
}
}
2.那么看完上方的思考,什么是线性表,链表呢?
线性表:是n个元素构成的有序序列。
几种基本操作:
(1).初始化一个空线性表
(2).根据索引i,返回响应元素
(3).在线性表中x第一次出现的位置
(4).再索引i前插入一个新元素x
(5).删除指定索引i的元素
(6).返回线性表的长度
java中如何定义线性表
class List
{
private Object[] data;
private int cur;//当前长度
}
(1)初始化空表
void MakeEmpty()
{
this.cur=0;
data=new Object[cur];
}
(2)根据索引返回元素
Object Find(int i)throws Exception
{
if(i<0||i>=cur)
{
throw new Exception("超出长度范围,无元素");
}
else {
return data[i];
}
}
(3)在线性表中x第一次出现的位置
int FindIndex(Object obj)
{
for(int i=0;i<cur;i++)
{
if(data[i]==obj)
return i;
}
return -1;
}
(4)在第i个位置插入一个值为x的新元素(i从1开始)
首先要做的事情就是先移动,将i-1后的元素全部后移一位,然后腾出空位,从最后一个元素开始挪。
void Insert(Object x,int i)throws Exception
{
if(i<0||i>=cur)
{
throw new Exception("超出长度范围,无元素");
}
else if(i!=cur) {
cur++;
for (int j = cur - 1; j >= i; j--) {
data[j] = data[j - 1];
}
data[i - 1] = x;
}
else if(i==cur)
{
data[i]=x;
}
}
(5)删除指定索引i的元素
和增加同理,在删除位置前移就可以了
void Delete(Object x,int i)throws Exception
{
if(i<0)
{
throw new Exception("超出长度范围,无元素");
}
else if(i!=cur) {
for (int j = i-1; j<cur; j++) {
data[j] = data[j+1];
}
cur--;
}
else if(i==cur)
{
cur--;
}
}
(6)返回线性表的长度
int Length()
{
return cur;
}
链表:不要求逻辑上相邻的两个元素物理上也相邻,通过“链”建立起元素之间的逻辑关系。
几种基本操作:
(1)求表长
(2)插入
(3)删除
(1)求表长
public int Length()
{
int length=0;
Node temp=head;
while(temp.next!=null)
{
length++;
temp=temp.next;
}
return length;
}
(2)插入
插入时一定要知道插入的前一个节点是谁,这样才能加入进去。
public void Insert(int index,Node node)
{
if(index<1||index>Length()+1)
{
System.out.println("插入位置不合法");
return;
}
int length=1;
Node temp=head;
while(head.next!=null)
{
if(index==length++)
{
node.next=temp.next;
temp.next=node;
return;
}
temp=temp.next;
}
}
(3)删除
public void Delete(int index)
{
if(index<1||index>Length()+1)
{
System.out.println(" 给定位置不合法");
return;
}
int length=1;
Node temp=head;
while(head.next!=null)
{
if(index==length++)
{
temp.next=temp.next.next;
return;
}
temp=temp.next;
}
}
3.广义表
什么是广义表呢?
广义表是线性表的推广
分析:可以将上述二元多项式看成关于x的一元多项式
上述二元多项式可以用复杂链表表示: