LeetCode(206)——Reverse Linked List

题目:

Reverse a singly linked list.


AC:

class Solution {
    public ListNode reverseList(ListNode head) {
        if (null == head || null == head.next) {
            return head;
        }
        
        ListNode prevNode = null;
        ListNode currNode = head;
        ListNode postNode = null;
        
        while (null != currNode) {
            postNode = currNode.next;
            currNode.next = prevNode;
            prevNode = currNode;
            currNode = postNode;
        }
        
        return prevNode;
    }
}

三指针,将节点依次进行翻转。

还有一种递归的解法。

猜你喜欢

转载自blog.csdn.net/weixin_39120845/article/details/79477787