Mã:
class Node{
int info;
Node next;
Node(){};
Node(int x, Node p){info=x;p=next;};
Node (int x){this(x,null);};
}
class MyList{
Node head,tail;
MyList(){head=tail=null;}
boolean isEmpty(){return head==null;}
void clear(){head=tail=null;}
void addLast(int x){
Node q=new Node(x);
if(isEmpty()){
head=tail=q;
return;
}
tail.next=q;
tail=q;
}
void addFirst(int y){
Node p=new Node(y);
if(isEmpty()){
head=tail=p;
return;
}
head.next=p;
head=p;
}
void traverse(){
Node p=head;
while(p!=null){
System.out.print(" "+ p.info);
p=p.next;
}
System.out.println();
}
void deleteFirst(){
if(isEmpty()){return;}
if(head==tail)head=tail=null; else
head=head.next;
}
void deleteLast(){
Node tmp;
if(isEmpty()) {return;}
if(head.next==null){head=tail=null; return;}
tmp=head;
while(tmp.next!=tail){tmp=tmp.next;}
tmp.next=null;
tail=tmp;
}
void addBefore(Node h,int x){
if(h==null) return;
if(isEmpty()) return;
Node f,p;
f=null; p=head;
while(p!=null){
if(p==h) break;
f=p;
p=p.next;
}
if(p==null) return;
if(f==null){addFirst(x); return;}
Node q=new Node(x);
q.next=h;
f.next=q;
}
void addAfter(Node h, int x){
if(h==null) return;
Node q=new Node(x);
q.next=h.next;
q.next=q;
if (h==tail) tail=q;
}
void addMany(int[]a){
int i,n;
n=a.length;
for(i=0;i<n;i++) addLast(a[i]);
}
Node search(int x){
Node p=head;
while(p!=null){
if(p.info==x) return(p);
p=p.next;
}
return null;
}
void delete(Node h){
if(h==null) return;
if(isEmpty()) return;
Node f,p;
f=null;
p=head;
while(p!=null){
if(p==h) break;
f=p;
p=p.next;
}
if(p==null)return;
if(f==null){
head=head.next;
if(head==null)tail=null;
return;
}
f.next=h.next;
if(f.next==null)tail=f;
}
void deletePosition(int k){
int i=0;
Node p=head;
while(p!=null){
if(i==k)break;
p=p.next;
i++;
}
delete(p);
}
void sort(){
Node pi,pj;
int t;
pi=head;
while(pi!=null){
pj=pi.next;
while(pj!=null){
if(pj.info<pi.info){
t=pi.info;
pi.info=pj.info;
pj.info=t;
}
pj=pj.next;
}
pi=pi.next;
}
}
int count(){
int i=0;
while(head!=null){
++i;
head=head.next;
}
return i;
}
}
public class Main{
public static void main(String[] args) {
MyList t=new MyList();
t.addFirst(1);
t.addLast(2);
t.addLast(3);
t.addLast(4);
t.addLast(5);
t.addLast(6);
t.addLast(7);
t.addLast(8);
t.deletePosition(2);
t.deleteFirst();
t.deleteLast();
t.traverse();
System.out.println();
System.out.println(t.count());
}
}
Giờ mình muốn gọi tới các hàm như addMany,delete,addAfter,addBefore... trong main thì ntn nhỉ, tại mình chả biết đưa đối số là Node vào như thế nào, ai giúp mình với, thanks [IMG]images/smilies/biggrin.png[/IMG][IMG]images/smilies/biggrin.png[/IMG]
View more random threads:
Không chỉ dừng lại ở việc sử dụng nguyên liệu cao cấp, mỗi công trình còn được "chăm sóc" bằng 4 dịch vụ xuất sắc của Tre Nghệ. Từ việc tư vấn, thiết kế đến thi công và hoàn thiện, mọi quy trình đều...
Chất Lượng và Sáng Tạo: Kiến Trúc...