206. 反转链表

package leetcode;

public class offer_24 {
    public ListNode reverseList(ListNode head) {
        
        //防止出现空链表
        if(head==null) {return null;}
        
        //未完成逆转的起始结点
        ListNode node=head.next;
        //记录当前结点的上一个结点
        ListNode pre=head;
        //记录每一轮逆序的头结点
        ListNode first=head;
        //当前结点
        ListNode cur;
        
        //使用头插法完成链表逆转
        while(node!=null) {
            cur=node;
            node=node.next;
            pre.next=cur.next;
            cur.next=first;
            first=cur;        
        }
        
        return first;
    }
}

 

posted on 2022-03-03 17:24  一仟零一夜丶  阅读(19)  评论(0)    收藏  举报