Insertion Sort List

Sort a linked list using insertion sort.

  1.  思想: 保持四个指针,循环last和p,以及从前向后插入的两个指针pre和q。
  2.  注意:几个指针之间的关系
  3. public ListNode insertionSortList(ListNode head) {
  4. if(head == null || head.next == null) return head;
  5. ListNode p = head.next;
  6. ListNode last = head;
  7. while(p!=null) {
  8. ListNode q = head;
  9. ListNode pre = head;
  10. while(p.val > q.val) {
  11. pre = q;
  12. q=q.next;
  13. }
  14. if(q==head) {
  15. last.next = p.next;
  16. p.next = head;
  17. head = p;
  18. } else if(q==p) {
  19. last = p;
  20. } else {
  21. last.next = p.next;
  22. pre.next = p;
  23. p.next = q;
  24. }
  25. p = last.next;
  26. }
  27. return head;
  28. }
posted @ 2014-07-15 21:52  purejade  阅读(67)  评论(0)    收藏  举报