class Node{//定义节点类
private int m_Data;
private Node m_Next;
Node(int data){
m_Data=data;
m_Next=null;
}
Node(int data,Node next){
m_Data=data;
m_Next=null;
}
void setData(int data){
m_Data=data;
}
int getData(){
return m_Data;
}
void setNext(Node next){
m_Next=next;
}
Node getNext(){
return m_Next;
}
}
class LinkList{//定义链表类
Node m_FirstNode;
LinkList(){
m_FirstNode=null;
}
LinkList(int data){
m_FirstNode=new Node(data);
}
String visitAllNode(){
Node next=m_FirstNode;
String s="";
while(next!=null){
s=s+next.getData()+"; ";
next=next.getNext();
}
return s;
}
void insertAtBegin(int data){
if(m_FirstNode==null)
m_FirstNode=new Node(data);
else
m_FirstNode=new Node(data,m_FirstNode);
}
void insertAfterId(int data,int id){
Node next=m_FirstNode;
if(next==null)
m_FirstNode=new Node(data);
else{
while(next.getNext()!=null && next.getData()!=id)
next=next.getNext();
next.setNext(new Node(data,next.getNext()));
}
}
boolean removeAtId(int id){
Node ahead=m_FirstNode;
Node follow=ahead;
if(ahead==null)
return false;
else if(ahead.getData()==id){
m_FirstNode=m_FirstNode.getNext();
return true;
}
else{
ahead=ahead.getNext();
while(ahead!=null){
if(ahead.getData()==id){
follow.setNext(ahead.getNext());
return true;
}
follow=ahead;
ahead=ahead.getNext();
}
return false;
}
}
void removeAll(){
m_FirstNode=null;
}
}
public class UseLinkList {//定义主类
public static void main(String[] args){
LinkList list=new LinkList(-1);
for(int i=0;i<10;i++){
list.insertAtBegin(i);
System.out.println(list.visitAllNode());
}
list.insertAfterId(10, 20);
System.out.println(list.visitAllNode());
if(list.removeAtId(-1))
System.out.println(list.visitAllNode());
else
System.out.println("no data in linklist");
list.removeAll();
}
}
链表的Java语言描述
最新推荐文章于 2024-09-10 10:22:48 发布