炫技操作--递归实现翻转链表(java)
递归实现链表的逆序
- leetcode 206题。 翻转链表
- 递归解法
- 普通方式实现链表翻转
- 链表专题
leetcode 206题。 翻转链表
leetcode链接用于测试
题目:描述
将一个链表翻转:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
递归解法
解题思路。递归每个子过程执行的都是相同的过程,只要我们在递归时,保证一个节点实现翻转,递归下去就会全部翻转过来,
所以就可以写出递归过程了,
leetcode 提供的链表结构:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
递归代码演示
class Solution {public ListNode reverseList(ListNode head) {//base case 节点为null或者只有一个节点时 无需翻转,返回自身if(head == null || head.next == null){return head;}//递归去操作每一个节点ListNode last = reverseList(head.next);//节点翻转head.next.next = head;head.next = null;return last;}
}
普通方式实现链表翻转
class Solution {public ListNode reverseList(ListNode head) {if(head == null || head.next == null){return head;}ListNode pre = null;ListNode cur = head;ListNode next = null;while(cur != null){next = cur.next;cur.next = pre;pre = cur;cur = next;}return pre;}
}
链表专题
leetcode–分隔链表
leetcoe–合并 K 个升序链表
leetcode–删除链表的倒数第N个节点