力扣 Offer24 反转链表

题目链接

思路:思路挺简单的,用一个临时节点B记录当前节点,另外一个节点A.next 指向 B,同时更更新节点A,A = A.next。这样就形成了反向?

代码

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

        ListNode cur = new ListNode(head.val);
        ListNode temp = null;
        
        head = head.next;
        while (head != null) {
            temp = new ListNode(head.val);
            head = head.next;

            temp.next = cur;
            cur = temp;
        }
        
        return cur;
    }
}
posted @ 2020-10-06 09:23  Bears9  阅读(66)  评论(0编辑  收藏  举报