package com.edu.dataStructure.Link;
interface List {
//获取线性表的长度
public int getLength() ;
//判断顺序表是不是为空
public boolean isEmpty();
//为顺序表添加元素
public void insert(int index,Object x) throws Exception;
//为顺序表删除元素
public void delete(int index) throws Exception;
//获取指定位置上的元素
public Object get(int index)throws Exception;
//查找顺序表中元素的位置
public int search(Object x)throws Exception;
//遍历元素
public void input();
}
package com.edu.dataStructure.Link;
import java.util.Scanner;
public class LinkList implements List {
public Node head ;
LinkList() {
head = new Node();
}
@Override
public int getLength() {
Node p = head.getNext();
int length = 0;
while (p != null) {
p = p.getNext();
length++;
}
return length;
}
@Override
public boolean isEmpty() {
Node p = head.getNext();
return p == null;
}
@Override
public void insert(int index, Object x) throws Exception {
Node p = head;
int j = -1;
while (p != null && j < index-1) {
p = p.getNext();
++j;
}
if (p == null || j > index-1) {
throw new Exception("参数错误");
}
Node s = new Node(x);
s.setNext(p.getNext());
p.setNext(s);
}
@Override
public void delete(int index) throws Exception {
Node p = head.getNext();
int j = 0;
while (p != null && j < index - 1) {
p = p.getNext();
j++;
}
p.setNext(p.getNext().getNext());
}
@Override
public Object get(int index) throws Exception {
Node p = head.getNext();
int j = 0;
while (p != null && j < index) {
p = p.getNext();
j++;
}
return p.getData();
}
public void create(int m)throws Exception{
Scanner sc=new Scanner(System.in);
for(int i=0;i<m;i++)
insert(getLength(),sc.next());
}
@Override
public int search(Object x) throws Exception {
Node p = head.getNext();
int j = 0;
while (p != null) {
if (p.getData().equals(x)) {
break;
}
p = p.getNext();
j++;
}
return j;
}
@Override
public void input() {
Node p = head.getNext();
while (p != null) {
System.out.print(p.getData() + " ");
p = p.getNext();
}
}
public Node getHead(){
Node p=head;
return p;
}
public LinkList mergeList_L(LinkList LA, LinkList LB) {
Node pa = LA.getHead().getNext();
Node pb = LB.getHead().getNext();
Node pc = LA.getHead();
int da, db;
while (pa != null && pb != null) {
da = Integer.valueOf(pa.getData().toString());
db = Integer.valueOf(pb.getData().toString());
if(da<=db){
pc.setNext(pa);
pc = pa;
pa = pa.getNext();
}else{
pc.setNext(pb);
pc = pb;
pb = pb.getNext();
}
}
pc.setNext(pa != null ? pa : pb); // 插入剩余结点
return LA;
}
}
测试类
package com.edu.dataStructure.Link;
public class test {
public static void main(String[] args) throws Exception{
LinkList list=new LinkList();
list.insert(0,1);
list.insert(1,2);
System.out.println(list.getLength());
}
}