标签:数据结构 init 反转 调用 new nod tween lang 链表
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]
声明一个虚头节点并指向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;
}
}
【数据结构】算法 Reverse Linked List II 反转链表的一部分
标签:数据结构 init 反转 调用 new nod tween lang 链表
原文地址:https://www.cnblogs.com/dreamtaker/p/14509149.html