剑指offer算法题:反转链表 ReverseList

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

循环

public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null)
            return head == null ? null : head;
        
        ListNode curNode = head,beforeNode = null,afterNode = null;
        
        while(curNode != null) {
            afterNode = curNode.next;
            curNode.next = beforeNode;
            if(afterNode == null) //最后一个节点
                break;
            beforeNode = curNode;
            curNode = afterNode;
        }
        return curNode;
    }

递归

	ListNode reverseHead = null; //反转后的头结点
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null)
            return head == null ? null : head;
        ReverseList(head,null);
        return reverseHead;
    }
    
    private void ReverseList(ListNode curNode,ListNode beforeNode) {
        if(curNode == null) {
            res = beforeNode;
            return;
        }
        ReverseList(curNode.next,curNode);
        curNode.next = beforeNode;
    }public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null)
            return head == null ? null : head;
        ListNode res = ReverseList(head,null);
        return res;
    }
    
    private ListNode ReverseList(ListNode curNode,ListNode beforeNode) {
        if(curNode == null) {
            return beforeNode;
        }
        ListNode res = ReverseList(curNode.next,curNode);
        curNode.next = beforeNode;
        return res;
    }
发布了239 篇原创文章 · 获赞 70 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43777983/article/details/104168676