牛客题霸反转链表题解
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=117&&tqId=35000&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking
title: 牛客题霸反转链表题解
date: 2020.11.05
categories: 算法
tags:
- 算法
反转链表
难度: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; } }