翻转列表

  1. public ListNode reverseList(ListNode head) {
  2. ListNode prev = null;
  3. while (head != null) {
  4. ListNode next = head.next;
  5. head.next = prev;
  6. prev = head;
  7. head = next;
  8. }
  9. return prev;
  10. }

链表归并排序

  1. class Solution {
  2. public ListNode sortList(ListNode head) {
  3. return sortList(head,null);
  4. }
  5. public ListNode sortList(ListNode head, ListNode tail) {
  6. if (head == null) {
  7. return head;
  8. }
  9. if (head.next == tail) {
  10. head.next = null;
  11. return head;
  12. }
  13. ListNode slow = head, fast = head;
  14. while (fast != tail) {
  15. slow = slow.next;
  16. fast = fast.next;
  17. if (fast != tail) {
  18. fast = fast.next;
  19. }
  20. }
  21. ListNode mid = slow;
  22. ListNode list1 = sortList(head, mid);
  23. ListNode list2 = sortList(mid, tail);
  24. ListNode sorted = merge(list1, list2);
  25. return sorted;
  26. }
  27. public ListNode merge(ListNode head1, ListNode head2) {
  28. ListNode dummyHead = new ListNode(0);
  29. ListNode temp = dummyHead, temp1 = head1, temp2 = head2;
  30. while (temp1 != null && temp2 != null) {
  31. if (temp1.val <= temp2.val) {
  32. temp.next = temp1;
  33. temp1 = temp1.next;
  34. } else {
  35. temp.next = temp2;
  36. temp2 = temp2.next;
  37. }
  38. temp = temp.next;
  39. }
  40. if (temp1 != null) {
  41. temp.next = temp1;
  42. } else if (temp2 != null) {
  43. temp.next = temp2;
  44. }
  45. return dummyHead.next;
  46. }
  47. }