1.2.1 Java 循环单链表
这里主要就是设置一个循环单链表(简称循环表)
其中的结点结构设置如下:
在循环表中设置一个头结点和一个尾结点引用,方便两个链表的合并
package dataStruct; /** * 循环单链表,简称循环表 * */ public class CircuSList { private SNode head; private SNode tail; public CircuSList(){ head = new SNode(0); head.next = head; } public void addHeadSNode(int data){ SNode s = new SNode(data); SNode current = head; while(current.next!= head){ current = current.next; } current.next = s; s.next = head; tail = s; head.setData(head.getData()+1); // 长度加1 } public static CircuSList combinCirList(CircuSList CL1, CircuSList CL2){ CL1.tail.next = CL2.head.next; CL2.tail.next = CL1.head; return CL1; } // 展示所有的单链表的结点信息 public void displayAllNode(){ SNode current = head.next;// 不显示头结点信息 while(current!=head){ current.display(); current = current.next; } System.out.println(); } public static void main(String[] args) { CircuSList cList = new CircuSList(); for(int i = 0; i < 10; i++){ cList.addHeadSNode(i); } CircuSList cList2 = new CircuSList(); for(int i = 0; i < 10; i++){ cList2.addHeadSNode(i); } // 测试程序运行结果 cList.displayAllNode(); CircuSList.combinCirList(cList, cList2).displayAllNode(); } }
总结:Java不能手动的进行垃圾回收机制,两个链表合并设置一个尾结点引用之后进行非常方便。