力扣92. 反转链表 II

1.使用vector辅助反转
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* reverseBetween(ListNode* head, int left, int right) { 14 vector<ListNode*> s; 15 ListNode * vhead = new ListNode(0, head); //添加哨兵节点,减少头结点改变的复杂讨论 16 ListNode * start = nullptr, *end = nullptr; 17 ListNode * pre = vhead; 18 for (int i = 0; i <= right; ++i) { 19 if (i == left - 1) { //找到子链的前节点 20 start = pre; 21 } 22 if (i >= left) { 23 s.push_back(pre); 24 } 25 if (pre -> next) { 26 pre = pre -> next; 27 if (i == right) { //找到子链外第一个节点指针赋值给end 28 end = pre; 29 } 30 } 31 } 32 for (int i = s.size() - 1; i > 0; --i) { 33 s[i] -> next = s[i - 1]; 34 s[i - 1] -> next = nullptr; 35 } 36 if (end) { 37 s[0] -> next = end; 38 } 39 40 start -> next = *s.rbegin(); 41 return vhead -> next; 42 } 43 };
2.纯使用链表进行反转(两趟)
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* reverseBetween(ListNode* head, int left, int right) { 14 ListNode *vhead = new ListNode(-1, head); 15 ListNode *pre, *cur, *next, *lhead, *rhead; 16 pre = vhead; 17 cur = head; 18 for (int i = 1; i <= right; ++i) { 19 next = cur -> next; 20 if (i == left) { 21 lhead = pre; //记录子链第一个节点的前节点 22 } 23 pre = cur; 24 cur = next; 25 } 26 rhead = next; //记录子链外的第一个节点 27 pre -> next = nullptr; //将子链的最后一个元素的next置空 28 29 cur = lhead -> next; //从子链第一个开始反转 30 while (cur != nullptr) { //头插法 31 next = cur -> next; 32 cur -> next = rhead; 33 rhead = cur; 34 cur = next; 35 } 36 //将子链拼回去 37 lhead -> next = rhead; 38 return vhead -> next; 39 } 40 };
3.纯列表 一趟
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* reverseBetween(ListNode* head, int left, int right) { 14 ListNode *vhead = new ListNode(0, head); 15 ListNode *pre = vhead, *cur = head, *nxt = head -> next; 16 ListNode *l; // 子链左边的节点 17 for (int i = 1; i < left; ++i) { // 将cur移动到left的位置 18 pre = cur; 19 cur = nxt; 20 nxt = nxt -> next; 21 } 22 l = pre; 23 for (int i = left; i < right; ++i) { // 将cur移动到right的位置 24 pre = cur; 25 cur = nxt; 26 nxt = nxt -> next; 27 cur -> next = pre; 28 } 29 l -> next -> next = nxt; //这里的nxt就是子链右边节点 30 l -> next = cur; 31 return vhead -> next; 32 } 33 };
浙公网安备 33010602011771号