leetcode算法题-链表-反转链表

题目描述

反转链表

代码实现

package com.leetcode.链表;
/**
 * Author:markusZhang
 * VM Args:
 * Date:Create in 2020/2/4 13:32
 */
public class 反转链表 {
    static class ListNode {
        int val;
        ListNode next;
        public ListNode(){}
        public ListNode(int val){
            this.val = val;
        }
    }
    //迭代方式
    //时间复杂度 O(n)
    //空间复杂度O(1)
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while(curr!=null){
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }
    //递归方式
    //时间复杂度O(n)
    //空间复杂度O(n)
    public ListNode reverseList1(ListNode head){
        if(head==null || head.next==null){
            return head;
        }
        ListNode p = reverseList1(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }

    public static void main(String[] args) {
        ListNode p = new ListNode(1);
        ListNode p1 = new ListNode(2);
        p.next = p1;
        ListNode p2 = new ListNode(3);
        p1.next = p2;
        ListNode p3 = new ListNode(4);
        p2.next = p3;
        new 反转链表().reverseList1(p);
    }
}

猜你喜欢

转载自blog.csdn.net/MarkusZhang/article/details/104169152