鱼C论坛

 找回密码
 立即注册
查看: 1356|回复: 0

[技术交流] C++刷LeetCode(92. 反转链表 II)【翻转链表】

[复制链接]
发表于 2020-7-20 10:41:25 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

  2. 说明:
  3. 1 ≤ m ≤ n ≤ 链表长度。

  4. 示例:

  5. 输入: 1->2->3->4->5->NULL, m = 2, n = 4
  6. 输出: 1->4->3->2->5->NULL

  7. 来源:力扣(LeetCode)
  8. 链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
  9. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码


  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. *     int val;
  5. *     ListNode *next;
  6. *     ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11.     ListNode* reverseBetween(ListNode* head, int m, int n) {
  12.         ListNode* res = new ListNode(-1);//关键点,至少保证四个长度
  13.         res -> next = head;
  14.         ListNode* temp1 = res;
  15.         int count = m - 1;
  16.         while(count > 0){
  17.             temp1 = temp1 -> next;
  18.             count--;
  19.         }
  20.         ListNode* temp2 = temp1 -> next;
  21.         ListNode* temp3 = temp2 -> next;
  22.         int gap = n - m;
  23.         while(gap > 0){
  24.             gap--;
  25.             ListNode* temp = temp3 -> next;
  26.             temp3 -> next = temp2;
  27.             temp2 = temp3;
  28.             temp3 = temp;
  29.         }
  30.         ListNode* temp4 = temp1 -> next;
  31.         temp1 -> next = temp2;
  32.         temp4 -> next = temp3;
  33.         return res -> next;
  34.     }
  35. };
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-28 01:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表