反转部分单向链表

  这道题需要注意换头节点的问题,然后就是先定位需要反转的链表的左右边界位置,然后在这个边界中进行链表的反转操作。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

class Node{
    public int val;
    public Node next;
    public Node(int val) {
        this.val = val;
    }
}

public class Main{
    public static Node reverseMiddleNode(Node head, int from, int to){
        if (head == null){
            return head;
        }
        Node fPre = null;
        Node tPos = null;
        int len = 0;
        Node node = head;
        while (node != null){
            len++;
            fPre = len == from - 1 ? node : fPre;
            tPos = len == to + 1 ? node : tPos;
            node = node.next;
        }
        if(from > to || from < 1 || to > len){
            return head;
        }
        Node node1 = fPre == null ? head : fPre.next;
        Node node2 = node1.next;
        Node next;
        node1.next = tPos;
        while (node2 != tPos){
            next = node2.next;
            node2.next = node1;
            node1 = node2;
            node2 = next;
        }
        if (fPre != null){
            fPre.next = node1;
            return head;
        }
        return node1;
    }
    public static void main(String[] args) throws IOException{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int len = Integer.parseInt(bf.readLine());    
        String[] elements = bf.readLine().split(" ");
        Node head = new Node(Integer.parseInt(elements[0]));
        Node node = head;
        for(int i = 1; i < len; i++){
            node.next = new Node(Integer.parseInt(elements[i]));
            node = node.next;
        }
        String[] params = bf.readLine().split(" ");
        int from = Integer.parseInt(params[0]);
        int to = Integer.parseInt(params[1]);
        Node res = reverseMiddleNode(head, from, to);
        while (res != null){
            System.out.print(res.val + " ");
            res = res.next;
        }
    }
}

你可能感兴趣的:(算法与数据结构)