92. Reverse Linked List II

网友投稿 228 2022-11-15

92. Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if (m >= n || head == null) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; for (int i = 1; i < m; i++) { if (head == null) { return null; } head = head.next; } ListNode premNode = head; ListNode mNode = head.next; ListNode nNode = mNode, postnNode = mNode.next; for (int i = m; i < n; i++) { if (postnNode == null) { return null; } ListNode temp = postnNode.next; postnNode.next = nNode; nNode = postnNode; postnNode = temp; } mNode.next = postnNode; premNode.next = nNode; return

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:384. Shuffle an Array
下一篇:XC7Z020框架设计 Firmware编写思路
相关文章

 发表评论

暂时没有评论,来抢沙发吧~