【LeetCode】92. 反转链表 II

素颜马尾好姑娘i 2022-05-11 11:20 263阅读 0赞

题目链接:https://leetcode-cn.com/problems/reverse-linked-list-ii/description/

题目描述

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

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

示例

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

解决方法

分两步:(1)反转位置 m 到 n 的链表 (2)连接分割后的三段链表

  1. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
  2. class Solution {
  3. public:
  4. ListNode* reverseBetween(ListNode* head, int m, int n) {
  5. if (m==n || !head->next) return head;
  6. //(1)反转位置 m 到 n 的链表
  7. ListNode *begin=head; //找到反转开始的位置
  8. int count=1;
  9. while(count<m){
  10. count++;
  11. begin=begin->next;
  12. }
  13. ListNode *new_head=NULL;//进行反转
  14. ListNode *temp=NULL;
  15. int num=n-m+1;
  16. while(num--){
  17. temp = begin->next;
  18. begin->next = new_head;
  19. new_head = begin;
  20. begin = temp;
  21. }
  22. //(2)连接三段链表
  23. ListNode *pummyhead=head;
  24. if (m>1){
  25. while(head->next->next) head=head->next;
  26. head->next=new_head;
  27. }
  28. else{
  29. pummyhead=new_head;
  30. }
  31. while(new_head->next) new_head=new_head->next;
  32. new_head->next=temp;
  33. return pummyhead;
  34. }
  35. };

发表评论

表情:
评论列表 (有 0 条评论,263人围观)

还没有评论,来说两句吧...

相关阅读