重排链表

题目描述:给定一个单链表 L 的头节点 head ,单链表 L 表示为:

L0 → L1 → … → Ln-1 → Ln
请将其重新排列后变为:

L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorder-list/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:链表遍历

首先,如果链表为空或链表只有一个节点,直接返回。

否则,首先用一个栈nodes记录所有的节点,并记录链表节点的数量count;

然后,记录插入的顺序,遍历到奇数位时,从头结点方向插入链表;遍历到偶数位时,从栈中取出节点(即从尾结点方向)插入链表。

  1. import com.kaesar.leetcode.ListNode;
  2. import java.util.Stack;
  3. public class LeetCode_143 {
  4. public static void reorderList(ListNode head) {
  5. if (head == null || head.next == null) {
  6. return;
  7. }
  8. // 所有节点
  9. Stack<ListNode> nodes = new Stack<>();
  10. // 链表节点的数量
  11. int count = 0;
  12. ListNode cur = head;
  13. while (cur != null) {
  14. count++;
  15. nodes.push(cur);
  16. cur = cur.next;
  17. }
  18. int front = 1, back = 0, i = 1;
  19. ListNode newCur = head;
  20. cur = head.next;
  21. // 分别从头结点和栈中遍历链表节点,然后按指定顺序插入新的头节点构成的链表中
  22. while (front + back < count) {
  23. i++;
  24. if (i % 2 == 1) {
  25. // 插入正向的节点
  26. newCur.next = cur;
  27. cur = cur.next;
  28. front++;
  29. } else {
  30. // 插入后面的节点
  31. newCur.next = nodes.pop();
  32. back++;
  33. }
  34. newCur = newCur.next;
  35. }
  36. // 最后,要将新的尾结点的next指向null
  37. newCur.next = null;
  38. }
  39. public static void main(String[] args) {
  40. ListNode head = new ListNode(1);
  41. head.next = new ListNode(2);
  42. head.next.next = new ListNode(3);
  43. head.next.next.next = new ListNode(4);
  44. head.next.next.next.next = new ListNode(5);
  45. System.out.println("-----重排之前-----");
  46. ListNode cur = head;
  47. while (cur != null) {
  48. System.out.print(cur.val + " ");
  49. cur = cur.next;
  50. }
  51. System.out.println();
  52. reorderList(head);
  53. System.out.println("-----重排之后-----");
  54. cur = head;
  55. while (cur != null) {
  56. System.out.print(cur.val + " ");
  57. cur = cur.next;
  58. }
  59. }
  60. }

【每日寄语】 人不怕有理想,不怕有梦想。也不管它又多大,又有多远!只要你客观的认清自己,在道德规范之内,坚持自己,做你想做的,一定会有收获的那一天!