java反转链表题

题目

给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。

数据范围: 0≤n≤1000
要求:空间复杂度 O(1) ,时间复杂度 O(n) 。

如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
在这里插入图片描述
示例1:

输入:
{1,2,3}
返回值:
{3,2,1}

示例2:

输入:
{}
返回值:
{}
说明:
空链表则输出空   

思路:设置next存放第一个值,以及后续移动的值;设置一个头zhuNode存最后一个值的地址,中间的nextValue存下一个地址,next放当前所在位置
在这里插入图片描述
换地址到next.next。
在这里插入图片描述
保存该next值给zhuNode,将nextValue保存的下一指针值给next,next继续循环。
在这里插入图片描述

import java.util.*;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null){
            return null;
        }
        int count = 1;
        ListNode next = new ListNode(head.val);
        next.next = head.next;
        ListNode zhuNode = null;
        while (next!=null){
            // 保存后面的值
            ListNode nextValue = next.next;
            // 存
            next.next = zhuNode;
            // 移动位置
            zhuNode = next;
            next = nextValue;
            count++;
        }
        if(count < 0 || count > 1001){
            return null;
        }
        return zhuNode;
    }
}

在这里插入图片描述
方法二:采用栈的方式,所以保存首地址Node2的值

// 方法二
        Stack<ListNode> stack = new Stack<>();
        while (head!=null){
            stack.push(head);
            head = head.next;
        }
        // 最后一个值出栈
        ListNode node = stack.pop();
        ListNode node2 = node;
        while (!stack.isEmpty()){
            ListNode value = stack.pop();
            node.next = value;
            node = node.next;
            count++;
        }
        node.next = null;
        if(count < 0 || count > 1000){
            return null;
        }
        // node2为最开始的首地址
        return node2;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值