力扣:链表翻转(经典算法题)(Leetcode)

将一个链表1->2->3->4->5,翻转成5->4->3->2->1

在idea里测试代码

public class T1108 {
    
    
    //注意要在前面加个static
    static class ListNode{
    
    
        int val;
        ListNode next;
        ListNode() {
    
    }
        ListNode(int val){
    
    this.val=val;}
        ListNode(int val,ListNode next){
    
    this.val=val; this.next=next;}
    }
    public static void main(String[] args) {
    
    
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        listNode1.next=listNode2;
        listNode2.next=listNode3;
        listNode3.next=listNode4;
        listNode4.next=listNode5;
        ListNode listNode = reverseList(listNode1);
        while (listNode!=null)
        {
    
    
            System.out.print(listNode.val+" ");
            listNode=listNode.next;
        }

    }
    public static ListNode reverseList(ListNode head) {
    
    
      ListNode pre = null;
      ListNode curr=head;
      while(curr!=null)
      {
    
    
          ListNode next = curr.next;
          curr.next = pre;
          pre =curr;
          curr =next;
      }
      return pre;
    }

}

在这里插入图片描述

STEP 1:ListNode next 记录的是下个点 next = current.next;
STEP 2:当下个节点被next记录,则当前节点的next指针就可以更改变成指向pre记录的节点
即:current.next =pre;(pre第一次为空)
STEP 3:pre用完就可以变成下一个,pre = current;
STEP 4: current = next;

将链表打印输出:

  ListNode listNode = reverseList(listNode1);
        while (listNode!=null)
        {
    
    
            System.out.print(listNode.val+" ");
            listNode=listNode.next;
        }

路途漫漫,但我又向你靠近一步啦~~~~✿✿ヽ(°▽°)ノ✿

猜你喜欢

转载自blog.csdn.net/weixin_43889487/article/details/121220343