Java链表反转的三种解法(Leetcode 206)

Reverse Linked List

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

第一种解法:迭代
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
    
    	// 单链表没有指向前一个节点的指针域,因此我们需要增加一个指向前一个节点的指针pre,
        // 用于存储每一个节点的前一个节点。此外,还需要定义一个保存当前节点的指针cur,以及下一个节点的						// next。
        // 定义好这三个指针后,遍历单链表,将当前节点的指针域指向前一个节点,之后将定义三个指针往后移动,
        // 直至遍历到最后一个节点停止

        //注意顺序的交接
        ListNode preNode = null;
        ListNode currNode = head;
        ListNode nextNode = null;
        while(currNode != null){
            nextNode = currNode.next;  //nextNode指向下一个节点
            currNode.next = preNode;   //将当前节点next域指向前一个节点
            preNode = currNode;		//preNode指针向后移动
            currNode = nextNode;	//curNode指针向后移动
        }
        return preNode;
    }
}
第二种解法:利用栈进行反转

关键点:先入栈,再出栈

public ListNode reverseList(ListNode head) {
        if (head == null){
            return null;
        }
        ListNode currNode = null;
        ListNode newNode = null;
        Stack<ListNode> left = new Stack<>();
        while (head != null){
            left.push(new ListNode(head.val));
            head = head.next;
        }
        while (left.size() != 0){
            ListNode node = left.pop();
            if (currNode == null){
                currNode = node;
                newNode = node;
                continue;
            }
            currNode.next = node;
            currNode = currNode.next;
        }

        return newNode;
    }
第三种解法:递归

这里引用官方的解法:

代码实现:

public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode p = reverseList(head.next);  //重点
        head.next.next = head;
        head.next = null;
        return p;
    }
总结

三种解法中其实利用栈来反转是最简单的,其次是迭代,最难的是递归,递归可以想成如果当前节点不是最后一个节点,就继续递归,直到最后一个,处理最后一个的场景,就是处理所有的场景。

我的公众号,里面有算法,Android,Kotlin,Flutter的分享。欢迎关注~
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值