此博客链接:https://www.cnblogs.com/ping2yingshi/p/12748095.html
反转链表
题目链接:https://leetcode-cn.com/problems/reverse-linked-list-ii/
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
题解:
思路:分三个部分,第一部分没有反转的前面节点,第二部分需要反转的节点,第三部分后面不需要反转的节点。
1.先找出没有反转的部分。
2.把反转部分用头插法反转。
3.在找出后半部分没有反转的节点。
但是代码报了一个错误,暂时还没有找到原因。
代码如下:
class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { ListNode now=new ListNode(0); ListNode cur=now; int count=1; while(count<m){ // ListNode node=head; // head=head.next; // cur.next=node; // cur=node; cur.next=head; cur=cur.next; head=head.next; count++; } while(count<=n) { ListNode node=head; head=head.next; node.next=cur; cur=node; count++; } while(head!=null) { cur.next=head; cur=cur.next; head=head.next; } return now.next; } }
原文:https://www.cnblogs.com/ping2yingshi/p/12748095.html