反转单链表中的部分链表
给定一个单向链表的头节点 head,以及两个整数 from 和 to,在单向链表上把第 from 个节 点到第 to 个节点这一部分进行反转
大致思路: 1、找到要反转部分链表的前一个节点fPre和后一个节点tPos,把反转的部分先反转,然后重新连接fPre和tPos; 2、若fPre为null,说明反转部分包括头节点,则返回的是反转部分的最后一个节点,即反转后的头结点,若不为空,则返回旧的头节点。
public Node reversePart(Node head,int from,int to){
int len = 0;
Node node1 = head;
Node fPre = null;
Node tPos = null;
开始遍历链表,找到fPre和tPos的位置,先找到fPre,之后的循环他会一直停在找到的位置,不会再变
while(node1 != null){
len++;
fPre = len == from - 1 ? node1 : fPre;
tPos = len == to + 1 ? node1 : tPos;
node1 = node1.next;
}
if(from > to || from < 1 || to > len){
return head;
}
//判断from的前一个节点是否为空,如果 fPre 为 null,说明反转部分是包含头节点的,
//则返回新的头节点,如果 fPre 不为 null,则返回旧的头节点。
//node1是要反转链表的头结点
node1 = fPre == null ? head : fPre.next;
Node node2 = node1.next;
//将反转部分的后一个节点与反转部分的头结点相连,很重要!!!
node1.next = tPos;
Node next = null;
//单链表反转的时候是判断头结点不等于null的情况下开始循环的,这个是要反转部分链表,因此类比的话就是
//要判断反转部分的下一个节点是否为空
while(node2 != tPos){
next = node2.next;
node2.next = node1;
node1 = node2;
node2 = next;
}
if(fPre != null){
fPre.next = node1;
return head;
}
return node1;
}
下一篇:
重建二叉树(牛客网)
