反转链表

1.题目

在这里插入图片描述

2.解法1(使用栈,还要破除原来的关系)

import java.util.Stack;
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        Stack<ListNode> stk = new Stack<>();
        while (head != null) {
            stk.push(head);
            head = head.next;
        }
        
       // 不创建虚假结点
        if (!stk.isEmpty()) head = stk.pop();
        ListNode cur = head;
        ListNode tmp = null;
        while (!stk.isEmpty()) {
            tmp = stk.pop(); 
            tmp.next = null;
            cur.next = tmp;
            cur = tmp;
        }  
        return head;
    }
}
import java.util.Stack;
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        Stack<ListNode> stk = new Stack<>();
        while (head != null) {
            stk.push(head);
            head = head.next;
        }
        
        // 假设我有一个虚假的头结点
        ListNode first = new ListNode(0);
        ListNode tmp = first;
        while (!stk.isEmpty()) {
            // 将本结点及next安排好后,再换结点
            head = stk.pop(); 
            head.next = null;
            tmp.next = head;
            tmp = head;
        }  
        return first.next;
    }

== 时间复杂度为O(n), 空间复杂度为O(n)==

解法2:使用3个结点(最佳解法)

import java.util.Stack;
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode pre = null;
        ListNode next = null;
        // 三个结点的移动
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}

时间复杂度为O(n), 空间复杂度为O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值