实验目的:
1.深入了解线性表的链式存储结构。
2.熟练掌握在链式存储结构上进行插入、删除等操作的算法。
实验内容:
1.线性表的链式存储结构。
2.链式存储结构上进行插入、删除等操作的算法。
实验要求:
1.定义IList接口
2.定义单链表结点类Node和单链表LinkList类
3.调用LinkList类,验证类的定义是否正确
Ilist接口:
package List;
public interface IList
{
public void clear();
public boolean isEmpty();
public int length();
public void insert(int i,Object x) throws Exception;
public void remove(int i) throws Exception;
public int indexof(Object x) throws Exception;
public void display();
public void create1(int n) throws Exception;
}
结点类Node:
package List;
public class Node
{
public Object data;
public Node next;
public Node()
{
this(null,null);
}
public Node(Object data)
{
this(data,null);
}
public Node(Object data,Node next)
{
this.data = data;
this.next = next;
}
}
单链表LinkList:
package List;
import List.IList;
import List.Node;
import java.util.Scanner;
public class LinkList implements IList
{
public Node head;
public LinkList()//构造方法
{
head = new Node();
}
//头插法
public void create1(int n) throws Exception
{
Scanner sc = new Scanner(System.in);
for(int j = 0;j<n;j++)
insert(0,sc.next());
}
//将头指针初始化
public void clear()
{
head.data = null;
head.next = null;
}
//判断指针是否为空
public boolean isEmpty()
{
return head.next == null;
}
//求带头结点的单链表的长度
public int length()
{
Node p = head.next;
int length = 0;
while(p!=null)
{
p = p.next;
++length;
}
return length;
}
//按值查找操作算法
public int indexof(Object x) throws Exception
{
Node p = head.next;
int j = 0;
while(p!=null&&!p.data.equals(x))
{
p = p.next;
++j;
}
if(p!=null)
return j;
else
return -1;
}
//插入算法
public void insert(int i,Object x) throws Exception
{
Node p = head;
int j = -1;
while(p!=null&&j<i-1)
{
p=p.next;
++j;
}
if(j>i-1||p==null)
throw new Exception("插入位置不合法!");
Node s = new Node(x);
s.next = p.next;
p.next = s;
}
//单链表的删除操作方法
public void remove(int i) throws Exception
{
Node p = head;
int j = -1;
while(p.next!=null&&j<i-1)
{
p = p.next;
++j;
}
if(j>i-1 ||p.next==null)
throw new Exception("删除位置不合法! ");
p.next = p.next.next;
}
//遍历
public void display()
{
int n=0;
Node p = head;
System.out.println("数值等于:");
while(p.next != null)
{
if(n==0)
{
System.out.print(p.data);
p = p.next;
}else
{
System.out.print("-->"+p.data);
p = p.next;
}
n++;
}
System.out.println();
}
}
test:
package List;
import java.util.Scanner;
public class test
{
public static void main(String args [])throws Exception
{
Scanner sc = new Scanner(System.in);
int n = 20;
LinkList L = new LinkList();
for(int i = 0;i<n;i++)
L.insert(i,i);
System.out.println("插入后:");
L.display();
System.out.println("插入的头结点后:");
L.create1(2);
L.display();
System.out.println("输入删除的位置:");
int k = sc.nextInt();
L.remove(k);
L.display();
System.out.println("输入查找的数值:");
int t = sc.nextInt();
if(L.indexof(t)==-1)
System.out.println("不存在");
else
System.out.println("存在");
}
}
实验结果: