关于循环链表的问题
可否只通过一个链接点引用而建立循环链表?
例如:
class RecList{
private Link current;
public RecList{
}
}
如何实现?
------解决方案--------------------public class LinkedList {
private Node header;
/**
* @return the header
*/
public Node getHeader() {
return header;
}
/**
* @param header the header to set
*/
public void setHeader(Node header) {
this.header = header;
}
public void printListContext(){
if (this.header == null){
System.out.println( "Null ");
return;
}
Node temp = this.header;
while(temp != null){
System.out.print(temp.getContext() + "--> ");
temp = temp.getNext();
}
System.out.print( "null ");
System.out.println();
}
public void resverce(){
if (this.header == null || this.header.getNext() == null){
return;
}
Node current = this.header,tempNext = this.header.getNext();
int cnt = 0;
while(tempNext != null){
cnt ++;
Node temp = current;
current = tempNext;
tempNext = tempNext.getNext();
if (cnt == 1){
temp.setNext(null);
}
current.setNext(temp);
}
this.header = current;
}
public void buildLinkedList(){
Node n4 = new Node( "4 ",null);
Node n3 = new Node( "3 ",n4);
Node n2 = new Node( "2 ",n3);
Node n1 = new Node( "1 ",n2);
Node n0 = new Node( "0 ",n1);
this.header = n0;
}
/**
* @param args
*/
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.buildLinkedList();
ll.printListContext();
ll.resverce();
ll.printListContext();
}
class Node {
private String context;
private Node next;
public Node(String context,Node n){
this.context = context;
this.next = n;
}
/**
* @return the context
*/
public String getContext() {
return context;
}
/**
* @return the next
*/
public Node getNext() {
return next;
}
/**
* @param next the next to set
*/
public void setNext(Node next) {
this.next = next;
}
}
}
这是我在别的帖子里给写的LinkedList,你可以参考一下,希望有帮助~
------解决方案-------------------- public class Check {
static class CycleList{
private int seq=0;
private CycleList next=null;
private static int currcapacity=0;
CycleList(int seq,CycleList next)
{
this.seq=seq;
this.next=next;
currcapacity++;
}
private void DeleteNode(CycleList node,CycleList head)
{
if(currcapacity> =2){
while(head.next!=node) head=head.next;
head.next=node.next;
node.next=node.next.next;
currcapacity--;
}
}
private boolean IsEmpty(){
return currcapacity <=1;
}
}
static int Josephu(int m,int n)
{
CycleList head=new CycleList(1,null);
CycleList last=head;
CycleList next=null;
for(int i=2;i <=n;i++)
{
next=new CycleList(i,null);
head.next=next;
head=next;
}
head.next=last;
head=last;
while (head.IsEmpty()==false)
{
for(int i=1; i <m;i++)