linkedlist cycle 插入时候排序
implement two method insert and print insert 要让 list 变成环 并且要排序
http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=201574&extra=&highlight=snapchat&page=1
My code:
public class LinkedListCycle {
// linked list cycle, sort when inserting
private ListNode dummy = new ListNode(-1);
public LinkedListCycle() {
dummy.next = dummy;
}
public void insert(ListNode node) {
if (dummy.next == dummy) {
dummy.next = node;
node.next = dummy;
}
else {
ListNode pre = dummy;
ListNode curr = dummy.next;
while (curr != dummy) {
if (curr.val < node.val) {
pre = pre.next;
curr = curr.next;
}
else {
pre.next = node;
node.next = curr;
break;
}
}
if (curr == dummy) {
pre.next = node;
node.next = dummy;
}
}
}
public void print() {
ListNode curr = dummy.next;
while (curr != dummy) {
System.out.println(curr.val);
curr = curr.next;
}
}
public static void main(String[] args) {
LinkedListCycle test = new LinkedListCycle();
ListNode n1 = new ListNode(5);
ListNode n2 = new ListNode(3);
ListNode n3 = new ListNode(6);
ListNode n4 = new ListNode(2);
ListNode n5 = new ListNode(7);
ListNode n6 = new ListNode(1);
ListNode n7 = new ListNode(8);
test.insert(n1);
test.insert(n2);
test.insert(n3);
test.insert(n4);
test.insert(n5);
test.insert(n6);
test.insert(n7);
test.print();
}
}
自己写了下。不难。
Anyway, Good luck, Richardo! — 09/27/2016