反转链表

2019-12-14  本文已影响0人  上杉丶零

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

package 剑指Offer.反转链表;

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode current = head;
        ListNode next = null;
        ListNode previous = null;

        while (current != null) {
            next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }

        return previous;
    }
}

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
上一篇下一篇

猜你喜欢

热点阅读