首页 > 其他 > 详细

LeetCode 92. 反转链表 II

时间:2020-03-06 20:22:28      阅读:70      评论:0      收藏:0      [点我收藏+]

题目链接: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 struct ListNode* reverseBetween(struct ListNode* head, int m, int n){
 2     if(head==NULL||head->next==NULL||m==n) return head;
 3     struct ListNode *new=(struct ListNode*)malloc(sizeof(struct ListNode));
 4     new->next=head;
 5     int i,j;
 6     struct ListNode *q=new,*pre;
 7     for(i=1;i<m;i++){
 8         pre=q;
 9         q=q->next;
10     }
11     struct ListNode *before=q,*front,*rear;
12     for(i=m;i<=n+1;i++){
13         if(i==m){
14             front=q->next;
15             rear=q->next;
16             q=q->next;
17         }else{
18             struct ListNode *tmp=q->next;
19             q->next=front;
20             front=q;
21             q=tmp;
22         }
23     }
24     rear->next=q;
25     before->next=front;
26     return new->next;
27 }

 

LeetCode 92. 反转链表 II

原文:https://www.cnblogs.com/shixinzei/p/12430270.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!