206. 反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
image.png

示例 1:
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
image.png
示例 2:
输入:head = [1,2] 输出:[2,1]
示例 3:
输入:head = [] 输出:[]

  1. package com.coco.learnalgorithmone.linkedlist;
  2. import com.coco.learnalgorithmone.linkedlist.entity.ListNode;
  3. import com.coco.learnalgorithmone.linkedlist.util.LinkedListUtils;
  4. /**
  5. * subject
  6. * 206. 反转链表
  7. * 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
  8. *
  9. * 示例 1:
  10. * 输入:head = [1,2,3,4,5]
  11. * 输出:[5,4,3,2,1]
  12. */
  13. public class ReverseList {
  14. public static void main(String[] args) {
  15. int[] arr = {1, 2, 3, 4, 5};
  16. ListNode head = reverseList1(LinkedListUtils.convertToLinkedList(arr));
  17. LinkedListUtils.printListNode(head);
  18. }
  19. public static ListNode reverseList1(ListNode head) {
  20. ListNode pre = null;
  21. ListNode curr = head;
  22. while (curr != null) {
  23. ListNode tmp = curr.getNext();
  24. curr.setNext(pre);
  25. pre = curr;
  26. curr = tmp;
  27. }
  28. return pre;
  29. }
  30. public static ListNode reverseList2(ListNode head) {
  31. ListNode pre = null;
  32. ListNode post;
  33. for (ListNode curr = head; curr != null; curr = post) {
  34. post = curr.getNext();
  35. curr.setNext(pre);
  36. pre = curr;
  37. }
  38. return pre;
  39. }
  40. }