letcode 反转链表java

描述

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

数据范围: n\leq1000n≤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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值