牛客题霸反转链表题解

反转链表

牛客题霸NC78

难度:Easy

题目描述:

输入一个链表,反转链表后,输出新链表的表头。

示例:
输入:
{1, 2, 3}
输出:
{3, 2, 1}
解决方法:
1.通过栈+尾插法实现

可以将所有节点入栈,然后逐个出栈,插入到链表尾部。

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) {
        
        Stack<ListNode> stack = new Stack<>();
        while(head != null){
            stack.push(head);
            head = head.next;
        }
        
        ListNode newHead = null;
        ListNode tail = null;
        while(!stack.isEmpty()){
            ListNode node = stack.pop();
            node.next = null;
            if(newHead == null){
                newHead = node;
                tail = node;
            }
            else{
                tail.next = node;
                tail = node;
            }
            
        }
        
        return newHead;
    }
}
2.头插法

我们要将链表逆序,可以遍历原链表,对每个节点采用头插法插入到新链表中即可实现反转。

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        
        ListNode newHead = null;
        
        while(head != null){
            ListNode nextNode = head.next;
            head.next = newHead;
            newHead = head;
            head = nextNode;
        }
        
        return newHead;
        
    }
}
3.通过递归实现

递归也可以实现链表反转,但是效率比较低。

/*
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 || head.next == null){
            return head;
        }
        // 反转head.next为开始的链表
        ListNode newHead = ReverseList(head.next);
        // 将head节点放到链表尾部
        head.next.next = head;
        head.next = null;
        
        return newHead;
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值