67,512
社区成员
发帖
与我相关
我的任务
分享
package SortInterface;
public class LinkList {//implements SortInterface{
private Node head;
private int length;
public LinkList(){
head=null;
length=0;
}
public void clearLinkList(){ //清空链表
head=null;
length=0;
}
public boolean isEmpty(){ //判断链表是否为空
return (length==0);
}
public void insert(int data) {
Node e = new Node(data);
if (length == 0) {
head=e;
}else {
e.next=head;
head=e;
}
length++;
}
////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
public boolean rmove(int data){
Node p=this.head,q=p;
if(length==0){
return false;
}
while(p!=null&&p.next.data!=data){
p=p.next;
}
if(p!=null){
q=p.next;
// p=q.next;
// q=null; //怎样删除结点q???? //怎样删除结点值为data的q结点????
length--; //
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
public void printLinkList(){
Node p=head;
while(p!=null){
System.out.print(" "+p.data);
p=p.next;
}
}
}
package SortInterface;
/**
*
* @author Administrator
*/
public class Node {
public int data;
public Node next;
public Node(){
}
public Node(int data){
this.data=data;
this.next=null;
}
}
package SortInterface;
/**
*
* @author Administrator
*/
public class TestList {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
LinkList link;
link=new LinkList();
link.insert(2);
link.insert(7);
link.insert(1);
link.insert(5);
link.insert(4);
link.printLinkList();
link.rmove(5);
System.out.println("\n删除元素后:");
link.printLinkList();
}
}
public int rmove(int data) {
Node p = this.head;
Node q = this.head;
if (length == 0) {
return 0;
}
int removeCount=0;
while(this.head.data==data){
this.head = this.head.next;
p = this.head;
q = this.head;
this.length--;
removeCount++;
}
p=p.next;
while (p != null){
if(p.data==data){
p=p.next;
q.next=p;
this.length--;
removeCount++;
}else{
p = p.next;
q=q.next;
}
}
return removeCount;
}