题目描述
解题方法1
- 其实和反转整个链表是一个原理,依然使用头插的方法。只需要将第from-1个节点当成头节点,将第to个节点当成最后一个节点即可。
- 首先遍历一遍链表,找到第from-1个节点phead和第to+1个节点ptail。
- 然后反转from–to的部分,最后再将反转后的链表与节点ptail连接起来。
- 代码如下:
public class Test {
public static void main(String[] args) throws Exception {
int[] arr = {10,20,30,40,50};
Node head = create(arr);
reverse(head,2,4);
for(Node p = head.next;p!=null;p=p.next){
System.out.println(p.val);
}
}
//反转链表一部分
public static Node reverse(Node head,int from,int to){
if(head==null || head.next==null){
return head;
}
int len = 0;//链表长度
Node headcopy = null; //第from-1个节点
Node tailcopy = null; //第tail+1个节点
for(Node p =head;p!=null;p=p.next){
headcopy = len==from-1?p:headcopy;
tailcopy = len==to+1?p:tailcopy;
len++;
}
if(from>to || from<1 || to>len-1){ //计算长度时多算了一个头节点这里要减掉
return head;
}
//开始反转操作
Node p = headcopy.next;
Node aftertail = headcopy.next; //第from个节点便是反转后的最后一个节点
headcopy.next=null;
while(p!=tailcopy){
Node temp = p.next;
p.next = headcopy.next;
headcopy.next = p;
p = temp;
}
aftertail.next = tailcopy; //把反转后的链表的最后一个节点与第to+1个节点进行连接
return head;
}
public static Node create(int[] arr){
Node head = new Node(0); //头节点
Node newnode = null; //指向新节点
Node tail = head; //指向链表尾节点
for(int a:arr){
newnode = new Node(a);
newnode.next = tail.next;
tail.next = newnode;
tail = newnode;
}
return head;
}
}
class Node{
int val;
Node next;
Node(int val){
this.val = val;
}
}
来源:CSDN
作者:zuiziyoudexiao
链接:https://blog.csdn.net/zuiziyoudexiao/article/details/104575235