翻转链表

剑指 Offer 24. 反转链表

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode reverseList(ListNode head) {
  11. if(head==null || head.next==null)
  12. return head;
  13. ListNode pre = head;
  14. ListNode now = pre.next;
  15. head.next =null;
  16. while(now!=null) {
  17. ListNode t = now.next;
  18. now.next = pre;
  19. pre = now;
  20. now = t;
  21. }
  22. return pre;
  23. }
  24. }

删除倒数第n个节点

  1. 对于可能删除头节点的情况,先创建一个虚拟节点指向头节点,使头节点作为第一个而不是第零个出现

148. 排序链表

恶心透了
image.png

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public ListNode sortList(ListNode head) {
  13. if(head==null||head.next==null)
  14. return head;
  15. int n = 0;
  16. ListNode now = head;
  17. while(now!=null) {
  18. now = now.next;
  19. n++;
  20. }
  21. ListNode dummy = new ListNode(0,head);
  22. for(int sub = 1; sub < n;sub=sub*2) {
  23. ListNode pre = dummy;
  24. ListNode curr = pre.next;
  25. while(curr!=null) {
  26. ListNode head1 = curr;
  27. for(int i = 1; i < sub && curr.next!=null ; i++) {
  28. curr = curr.next;
  29. }
  30. ListNode head2 = curr.next;
  31. curr.next = null;
  32. curr = head2;
  33. for(int i = 1; i < sub && curr!=null && curr.next!=null ;i++) {
  34. curr = curr.next;
  35. }
  36. ListNode next = null;
  37. if(curr!=null) {
  38. next = curr.next;
  39. curr.next = null;
  40. }
  41. ListNode merged = merge(head1,head2);
  42. pre.next = merged;
  43. while(pre.next!=null)
  44. pre = pre.next;
  45. curr = next;
  46. }
  47. }
  48. return dummy.next;
  49. }
  50. public ListNode merge(ListNode head1, ListNode head2) {
  51. ListNode dummyHead = new ListNode(0);
  52. ListNode temp = dummyHead, temp1 = head1, temp2 = head2;
  53. while (temp1 != null && temp2 != null) {
  54. if (temp1.val <= temp2.val) {
  55. temp.next = temp1;
  56. temp1 = temp1.next;
  57. } else {
  58. temp.next = temp2;
  59. temp2 = temp2.next;
  60. }
  61. temp = temp.next;
  62. }
  63. if (temp1 != null) {
  64. temp.next = temp1;
  65. } else if (temp2 != null) {
  66. temp.next = temp2;
  67. }
  68. return dummyHead.next;
  69. }
  70. }