当前位置:  首页>> 技术小册>> 数据结构与算法(下)

题目描述

输入一个链表,反转链表后,输出新链表的表头。

解法

解法一

利用头插法解决。

  1. /**
  2. * @author bingo
  3. * @since 2018/11/22
  4. */
  5. /*
  6. public class ListNode {
  7. int val;
  8. ListNode next = null;
  9. ListNode(int val) {
  10. this.val = val;
  11. }
  12. }*/
  13. public class Solution {
  14. /**
  15. * 反转链表
  16. * @param head 链表头部
  17. * @return 反转后的链表
  18. */
  19. public ListNode ReverseList(ListNode head) {
  20. if (head == null || head.next == null) {
  21. return head;
  22. }
  23. ListNode dummy = new ListNode(-1);
  24. dummy.next = null;
  25. ListNode p1 = head;
  26. ListNode p2 = p1.next;
  27. while (p1 != null) {
  28. p1.next = dummy.next;
  29. dummy.next = p1;
  30. p1 = p2;
  31. if (p1 == null) {
  32. break;
  33. }
  34. p2 = p1.next;
  35. }
  36. return dummy.next;
  37. }
  38. }

解法二:递归

  1. /**
  2. * @author bingo
  3. * @since 2018/11/22
  4. */
  5. /*
  6. public class ListNode {
  7. int val;
  8. ListNode next = null;
  9. ListNode(int val) {
  10. this.val = val;
  11. }
  12. }*/
  13. public class Solution {
  14. public ListNode ReverseList(ListNode head) {
  15. if (head == null || head.next == null) {
  16. return head;
  17. }
  18. ListNode next = ReverseList(head.next);
  19. ListNode cur = next;
  20. while (cur.next != null) {
  21. cur = cur.next;
  22. }
  23. cur.next = head;
  24. head.next = null;
  25. return next;
  26. }
  27. }

测试用例

  1. 功能测试(链表中有多个结点/只有一个节点);
  2. 特殊输入测试(链表头节点为空指针)。

该分类下的相关小册推荐: