牛客网高频算法题系列-BM1 反转链表

题目描述

给定一个单链表的头结点pHead(该头节点是有值的),长度为n,反转该链表后,返回新链表的表头。

原题目见:BM1 反转链表

解法一:结点反转

  • 首先,如果head为空或者只有一个结点,直接返回。
  • 否则,分别用first和next指针指向链表的前两个结点,并将它们的next指针域反转,然后继续往后遍历处理链表的后续结点直到将最后一个结点反转。注意,需要将head头结点的next指向null。
  • 最后,返回first结点,即为反转后的新链表的头结点。

解法二:递归法

  • 同样的,首先需要判断,如果head为空或者只有一个结点,直接返回。
  • 否则,通过递归的方式来处理,递归的处理流程如下:
    • 递归的终结条件是head结点为空或者没有下一个结点;
    • 否则,递归得到head.next的反转链表为reverse,然后将reverse的next指针指向head,同样要记住需要将head头结点的next指向null。
  1. public class Bm001 {
  2. /**
  3. * 反转结点
  4. *
  5. * @param head 原链表的头结点
  6. * @return
  7. */
  8. public static ListNode reverseList(ListNode head) {
  9. // 如果链表为空或者只有一个节点,不需要反转,直接返回原链表
  10. if (head == null || head.next == null) {
  11. return head;
  12. }
  13. ListNode first = head, second = head.next;
  14. first.next = null;
  15. while (first != null && second != null) {
  16. ListNode temp = first;
  17. first = second;
  18. second = second.next;
  19. first.next = temp;
  20. }
  21. return first;
  22. }
  23. /**
  24. * 递归法
  25. *
  26. * @param head 原链表的头结点
  27. * @return
  28. */
  29. public static ListNode reverseList2(ListNode head) {
  30. // 递归的终止条件
  31. if (head == null || head.next == null) {
  32. return head;
  33. }
  34. // 递归处理
  35. ListNode reverse = reverseList2(head.next);
  36. head.next.next = head;
  37. head.next = null;
  38. return reverse;
  39. }
  40. public static void main(String[] args) {
  41. // 测试用例
  42. ListNode head = ListNode.testCase1();
  43. System.out.println("反转之前");
  44. ListNode.print(head);
  45. System.out.println("反转之后");
  46. ListNode newHead = reverseList(head);
  47. ListNode.print(newHead);
  48. System.out.println("再次反转之后");
  49. ListNode newHead2 = reverseList2(newHead);
  50. ListNode.print(newHead2);
  51. }
  52. }

牛客网高频算法题系列-BM1 反转链表 - 图1
牛客网高频算法题系列-BM1 反转链表 - 图2
相信坚持的力量!