/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } *///核心思想,利用cur和Curnext分别记录head的前驱和cur的前驱,再去改变箭头方向class Solution {public ListNode reverseList(ListNode head) {if(head==null)return head;//为空的链表if(head.next==null)return head;//一个值反转还是自己ListNode cur=head.next;ListNode Curnext;head.next=null;//第一个节点的值会变成转换完成的最后一个节点,需要手动改变指向nullwhile(cur!=null){Curnext=cur.next; cur.next=head;//改变箭头方向head=cur;cur=Curnext;}return head;}}

反转一个单链表