import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Solution {
public static class LinkNode {
LinkNode next;
int val;
public LinkNode(int v) {
this.val = v;
}
}
public LinkNode head;
public void insert(int val) {
LinkNode node = new LinkNode(val);
if (head == null) {
head = node;
head.next = node;
} else {
if (node.val < head.val) {
LinkNode tail = head;
while (tail.next != head) tail = tail.next;
node.next = head;
tail.next = node;
head = node;
} else {
LinkNode p = head;
while (true) {
if (p.next == head || p.next.val > val) {
LinkNode next = p.next;
p.next = node;
node.next = next;
break;
}
p = p.next;
}
}
}
}
public void print() {
LinkNode p = head;
if (p == null) return;
while (true) {
System.out.print(p.val + " ");
p = p.next;
if (p == head) {
break;
}
}
System.out.println();
}
public static void main(String[] args) {
Solution s = new Solution();
s.print();
s.insert(5);s.print();
s.insert(3);s.print();
s.insert(4);s.print();
s.insert(2);s.print();
s.insert(1);s.print();
}
}
没有评论:
发表评论