采用循环单链表做为线性表的存储结构,编写成员方法:删除运算。
删除成功,输出删除后的线性表的所有元素
删除失败,输出“error”
输入样例:
5 2 8 7 4 6
4
输出样例:
2 8 7 4
输入样例:
5 2 8 7 4 6
7
输出样例:
error
函数接口定义:
方法定义:
public void remove(int pos) throws Exception
参数pos表示删除的元素位置
裁判测试程序样例:
import java.util.Scanner;
class Input {
private static Scanner sc = new Scanner(System.in);
static int inputInt(){
return sc.nextInt();
}
}
class Node{
int data;
Node next;
public Node( ){
data=0 ;
next=null;
}
public Node( int obj , Node nt) {
data=obj ;
next=nt;
}
}
class LinkList{
public Node head ;
public LinkList () //创建循环单链表,代码省略
{...... }
public void display() //显示线性表的所有元素,代码省略
{...... }
/* 请在这里填写答案 */
}
public class Main{
public static void main(String args[]){
LinkList L = new LinkList();
int pos = Input.inputInt();
try{
L.remove(pos);
L.display();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
参考答案:
public void remove(int pos) throws Exception{
Node s = head;
int j=0,flag=0;
while(s.next.data!=head.data) {
j++;
s=s.next;
}
s = head;
for(int i=0;i<j;i++) {
if(i==pos) {
s.next = s.next.next;
break;
}
s = s.next;
flag++;
}
if(flag>=j) {
throw new IllegalArgumentException("error");
}
}