15____反转链表

题目描述:

输入一个链表,反转链表后,输出新链表的表头。

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        
        ListNode pre=null;   //当前结点的前一个结点
        ListNode next=null;   //当前结点的后一个结点
        
        if(head==null){
            return null;
        }
        
        while(head!=null){
            next=head.next;   //保存下一个结点
            head.next=pre;    //逆序反转
            pre=head;      //更新
            head=next;   //更新
        }
        return pre;
    }
}

共有三个结点:

当前结点 head;

当前结点的前一个结点 pre;

当前结点的后一个结点 next;

猜你喜欢

转载自www.cnblogs.com/xbfchder/p/11457178.html