- 递归反转链表
(1)反转整个链表
/**
* 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) {
if (head == null || head.next == null) return head;//base case:empty or only one node, reverse与否一个样,so simply return head
ListNode last = reverse(head.next);//recursion: new head = reverse(old head)先递归再对当前node进行操作,那么会先递归到尽头,然后从后向前依次执行操作,即修改link
head.next.next = head;//modify link: point the last node of the reversed list to head
head.next = null;//modify link:point head to null
return last;//return new head
}
}
(2)反转前N个节点
(3)反转M节点到N节点
(4)K个一组反转链表
版权声明:本文为DecafTea原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。