题意
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
题意
不是很难,直接上代码
代码演示
/**
* 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; }
* }
*/
// 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) {
if (left==right)
return head;
ListNode pre=head;
ListNode leftNode=new ListNode();
ListNode rightNode=new ListNode();
int flag=1;
ListNode prelef=new ListNode();
while(head!=null)
{
if(flag==left-1)
prelef=head;
if(flag==left)
{
leftNode=new ListNode(head.val,head.next);
}
if(flag==right)
{
rightNode=new ListNode(head.val,head.next);
break;
}
head=head.next;
flag++;
}
ListNode leftNext=leftNode.next;
ListNode Next=leftNext.next;
leftNode.next=rightNode.next;
//这边打个标记
while (leftNext!=rightNode.next)
{
leftNext.next=leftNode;
leftNode=leftNext;
leftNext=Next;
if (Next!=null)
Next=Next.next;
}
if(left==1)
return leftNode;
prelef.next=leftNode;
return pre;
}
}
效果
info
解答成功:
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:36 MB,击败了71.42% 的Java用户