• 【数据结构】算法 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;
        }
    }
    
  • 相关阅读:
    002使用代码和未经编译的XMAL文件创建WPF程序
    001使用代码创建WPF应用程序
    制作地图PPT
    数据库基本知识学习(sql server)
    虚拟现实技术对人类是福还是祸?
    计算机中的数学
    软件架构
    extracts
    bootstrap
    omron欧姆龙自动化应用
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14509149.html
Copyright © 2020-2023  润新知