24、反转链表

2019-09-27  本文已影响0人  GIndoc
输入一个链表,反转链表后,输出新链表的表头。

题目链接:https://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca

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

    ListNode(int val) {
        this.val = val;
    }
}*/

public class Solution {
    public ListNode ReverseList(ListNode head) {
        
        if(head==null) return null;
        

        // a->b->c->d
        // a->b->c  d
        // 当current指向d时,需要一个变量last保存c
        ListNode current = head.next;
        ListNode last = head;
        last.next = null;
        
        while(current!=null){
            last = current;
            current = current.next;
            last.next = head;
            head = last;
        }
        return head;
    }
    
}
上一篇下一篇

猜你喜欢

热点阅读