zoukankan      html  css  js  c++  java
  • 【数据结构】算法 Reverse Linked List II 反转链表的一部分

    Reverse Linked List II 反转链表

    Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

    将链表从第left节点开始到第right个节点结束的一段进行翻转

    Input: head = [1,2,3,4,5], left = 2, right = 4
    Output: [1,4,3,2,5]
    

    虚头法 dummy head+递归

    声明一个虚头节点并指向head,

    首先寻找到left的前一个node,然后开始调用reversN,reversN最后返回的node就是反转后的头节点。将之前第left-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 reverseBetween(ListNode head, int left, int right) {
            ListNode vitrualnode = new ListNode(0, head);
                    ListNode pre = vitrualnode;//
                    int move = left-1;
                    while(move>0){
                        pre= pre.next;
                        move--;
                    }
                    pre.next = reversN(pre.next, right - left + 1);
    
                    return vitrualnode.next;
        }
        public ListNode reversN(ListNode head,int n){
            if(n ==1){
                return head;
            }
            ListNode tail = head.next;
            ListNode p = reversN(head.next,n-1);
            head.next= tail.next;
            tail.next = head;
            return p;
        }
    }
    
  • 相关阅读:
    带不带protype的区别
    一些方法(自己的认知)
    事件
    简单笔记
    freemarker Velocity获取request,session
    Freemaker中使用中括号来包含标签
    FreeMarker自定义标签
    Velocity模版自定义标签
    前端常用代码
    Eclipse中配置Ehcache提示信息
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14509149.html
Copyright © 2011-2022 走看看