天天看點

java 循環單連結清單_java循環單連結清單實作約瑟夫環

展開全部

看了你的代碼,不是很明白,給你提幾個建議吧:

1、不需要tail節點

2、remove方法應該32313133353236313431303231363533e59b9ee7ad9431333335313835對删除節點前面的節點操作,而不是使用數字找

給你我修改的LinkList類,你參考一下:public class LinkList {

private Node head;

int curlen = 0;

// 建立連結清單

public void createlist(int code) throws Exception {

insert(curlen, code);

}

public void insert(int i, int code) throws Exception {

Node s = new Node(code);

if (i == 0) {

s.setNext(head);

head = s;

}

Node p = head;

int j = 0;

while (p != null && j 

p = p.getNext();

j++;

}

if (j > i || p == null) {

throw new Exception("插入位置不合理");

}

s.setNext(p.getNext());

p.setNext(s);

//tail = s;

//tail.setNext(head);

curlen = curlen + 1;

}

public void remove(int i) throws Exception {

Node p = head, q = null;

int j = 0;

i = i - 1;

while (j 

q = p;

p = p.getNext();

j++;

}

if (j > i || p == null)

throw new Exception("删除位置不合法");

if (q == null) {

//tail.setNext(p.getNext());

head = head.getNext();

} else

q.setNext(p.getNext());

curlen = curlen - 1;

}

public void remove(Node p) throws Exception {

if(p.getNext()==p){

p=null;

head=null;

}

else{

Node q = p.getNext();

p.setNext(q.getNext());

}

curlen = curlen - 1;

}

public void out(int m) throws Exception {

Node p = head;

if(m==1){

System.out.print("按照順序出列");

return;

}

int count = 1;

int n=m-1;

while (curlen > 0) {

if (count == n) {

System.out.print(p.getNext().getData() + "  ");

remove(p);

count = 1;

} else {

count++;

}

p = p.getNext();

}

}

public void display() {

Node node = head;

for (int i = 0; i 

System.out.print(node.getData() + " ");

node = node.getNext();

}

System.out.println();

}

}