https://leetcode-cn.com/problems/reverse-linked-list/
    给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

    示例 1:

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

    输入:head = [1,2]
    输出:[2,1]
    示例 3:

    输入:head = []
    输出:[]

    https://www.bilibili.com/video/BV1KZ4y157Up?from=search&seid=7613549620764321902

    image.png
    问题分析:这道算法题实际上就是如何让后一个节点指向前一个节点。定义三个指针,pre, cur,tmp,tmp节点主要是为了在断裂前,保存当前节点的后驱节点,防止链表断裂

    1. package linkedlist;
    2. class ListNode{
    3. int val;
    4. ListNode next;
    5. ListNode(){}
    6. public ListNode(int val){
    7. this.val = val;
    8. }
    9. public ListNode(int val, ListNode next){this.val = val; this.next = next;}
    10. }
    11. public class ReverseList {
    12. public static void main(String[] args) {
    13. ListNode listNode = new ListNode(3);
    14. ListNode listNode1 = new ListNode(5);
    15. ListNode listNode2 = new ListNode(6);
    16. ListNode listNode3 = new ListNode(2);
    17. listNode.next = listNode1;
    18. listNode1.next = listNode2;
    19. listNode2.next = listNode3;
    20. ListNode h = listNode;
    21. while (h!=null){
    22. System.out.print(h.val+" ");
    23. h = h.next;
    24. }
    25. ListNode pre = reverseList(listNode);
    26. System.out.println("-------翻转后的链表");
    27. while (pre!=null){
    28. System.out.print(pre.val+" ");
    29. pre = pre.next;
    30. }
    31. }
    32. public static ListNode reverseList(ListNode head){
    33. //设置三个临时指针,pre,cur,tmp
    34. //tmp主要是为了保证链表不断裂,在后驱节点指向前驱节点前记录当前节点的后驱节点
    35. ListNode pre = null;
    36. ListNode cur = head;
    37. ListNode tmp;
    38. while (cur!=null){//循环以下过程,直至当前节点为空,反转结束,返回pre指针
    39. tmp = cur.next;//在断裂前记录当前节点的后驱节点
    40. cur.next = pre;//断裂,使得当前节点指向前驱节点,进行翻转
    41. pre = cur;//pre往后移
    42. cur = tmp;//cur往后移
    43. }
    44. return pre;
    45. }
    46. }