LeetCode 92. 反转链表 II

题目链接: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 }

 

posted @ 2020-03-06 19:13  wydxry  阅读(209)  评论(0编辑  收藏  举报
Live2D