初学java语言,感觉到java语言的面向对象的特性之强大。
java的对象就是一个指针,使用new创建对象就是对指针申请空间。
public class linklist{ static int MAX_LINK_NUM = 100; int data; //实例变量
linklist next; //引用, 即C语言的指针
linklist(){ //使用构造方法初始化链表头 data = 0; next = null; } /* *往链表L内插入一个链表,其数据为data */ public linklist InsertLink(linklist L, int data){ linklist s, r; r = L; while(r.next != null){ r = r.next; } s = new linklist(); s.data = data; r.next = s; s.next = null; return L; } public int GetLinkNum(linklist L){ linklist r; int num = 0; r = L.next; while(r != null){ num++; r = r.next; } return num; } /* *删除链表L的第num个链表 *num : 1~MAX_LINK_NUM */ public linklist DeleteLink(linklist L, int num){ linklist r, p; /*p为第num-1个链表。r为第num个链表*/ int num1, num2; if(num > L.GetLinkNum(L)){ System.out.println("所要删除的链表不存在!"); return L; } r = p = L; num1 = num2 = num; while(num1 != 1){ p = p.next; num1--; } while(num2 != 0){ r = r.next; num2--; } p.next= r.next; return L; } public static void main(String args[]){ linklist L, r; L = new linklist(); for(int i = 1; i < 11; i++){ L.InsertLink(L, i); } r = L.next; while(r != null){ System.out.println(r.data); r = r.next; } int num = L.GetLinkNum(L); System.out.print("链表长度是:"); System.out.println(num); L.DeleteLink(L, 2); r = L.next; while(r != null){ System.out.println(r.data); r = r.next; } num = L.GetLinkNum(L); System.out.print("链表长度是:"); System.out.println(num); L.DeleteLink(L, 12); r = L.next; while(r != null){ System.out.println(r.data); r = r.next; } num = L.GetLinkNum(L); System.out.print("链表长度是:"); System.out.println(num); } }
|
阅读(3511) | 评论(0) | 转发(0) |