栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

letcode 反转链表java

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

letcode 反转链表java

描述

给定一个单链表的头结点pHead,长度为n,反转该链表后,返回新链表的表头。

数据范围: nleq1000n≤1000

要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。

如当输入链表{1,2,3}时,

经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。

以上转换过程如下图所示:

 1,递归法

首先定义Node:

java

public static class Node {
	public int value;
	public Node next;

	public Node(int data) {
		this.value = data;
	}
}

反转方法如下:

java

public Node reverse(Node head) {
    if (head == null || head.next == null)
        return head;
    Node temp = head.next;
    Node newHead = reverse(head.next);
    temp.next = head;
    head.next = null;
    return newHead;
}

递归实质上就是系统帮你压栈的过程,系统在压栈的时候会保留现场。

 2,遍历法
public ListNode ReverseList2(ListNode head) {

    //1->2->3->4
    ListNode  pre=null;
    ListNode  nextNode=null;
    while (head!=null){

        nextNode= head.nextNode;
        head.nextNode=pre;
        pre=head;
        head=nextNode;
    }

    return pre;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/678210.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号