package com.dby.link;
/** * Created by suzunshou on 2016/4/11. * 链表的元素不能随机访问 * 元素前面和后面不会出现多个元素相连的情况 * 元素相互依赖,串联而成 * 链表只有一个表头 * 循环链表首尾相连,尾结点指向首结点 */
public class LinkedList {
private class Node {
private Object data;
private Node next = null;
public Node(Object data) {
this.data = data;
}
}
private Node first = null;
private Node last = null;
private int size;
public void insert(Object data, int index) {
Node newNode = new Node(data);
if (first == null) {
first = newNode;
first.next = first;
return;
}
if (index - 1 == 0) {
newNode.next = first.next;
first.next = newNode;
return;
}
Node curr = first.next;
int count = 0;
while (curr != first && count < index - 2) {
curr = curr.next;
count++;
}
if (count == index - 2) {
newNode.next = curr.next;
curr.next = newNode;
}
if (newNode == first.next) {
first = newNode;
}
size++;
}
public void output_josephus(int m) {
Node curr = first;
while (curr.next != curr) {
for (int i = 1; i < m; i++) {
curr = curr.next;
}
Node del = curr.next;
System.out.println(del.data);
curr.next = curr.next.next;
del = null;
}
System.out.println(curr.data);
curr = null;
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
for (int i = 1; i < 8; i++) {
ll.insert2(i, i);
}
ll.output_josephus(2);
}
}