力扣 题目92- 反转链表 II
题目
题解
参考 力扣 题目25-- K 个一组翻转链表 的做法使用栈即可
代码
1 #include<iostream> 2 #include<vector> 3 #include<stack> 4 using namespace std; 5 struct ListNode { 6 int val; 7 ListNode* next; 8 ListNode() : val(0), next(nullptr) {} 9 ListNode(int x) : val(x), next(nullptr) {} 10 ListNode(int x, ListNode* next) : val(x), next(next) {} 11 }; 12 13 class Solution { 14 public: 15 ListNode* reverseBetween(ListNode* head, int left, int right) { 16 if (head == nullptr || left == right) { 17 return head; 18 } 19 //创造一个无关的结点并连接原来的链表 就可以使原本的头结点 普通化 20 ListNode* result = new(ListNode); 21 result->next = head; 22 //记录反转开头位置(即left-1) 23 ListNode* begin= head; 24 stack<ListNode*> reversal; 25 //重置头结点为新 26 head = result; 27 for (int i = 0; i<= right; i++) { 28 //记录栈 29 if (left <= i&& i<= right) { 30 reversal.push(head); 31 } 32 //记录反转开头位置(即left-1) 33 if (i == left - 1) 34 { 35 begin = head; 36 } 37 head = head->next; 38 } 39 //栈出 40 while (!reversal.empty()) 41 { 42 begin->next = reversal.top(); 43 begin = begin->next; 44 reversal.pop(); 45 } 46 //接上反转后链表 47 begin->next = head; 48 return result->next; 49 } 50 }; 51 52 53 void listnum(ListNode& list, vector<int>& vectorlist) { 54 ListNode* headlist = &list; 55 for (int i = 0; i < vectorlist.size(); i++) { 56 ListNode* p; 57 p = (struct ListNode*)malloc(sizeof(struct ListNode*)); 58 p->val = vectorlist[i]; 59 headlist->next = p; 60 headlist = headlist->next; 61 } 62 headlist->next = NULL; 63 } 64 int main() { 65 Solution sol; 66 ListNode list1(3); 67 vector<int> vectorlist1 = { 5 }; 68 listnum(list1, vectorlist1); 69 ListNode* list = sol.reverseBetween(&list1,1,2); 70 for (int i = 0; list != NULL; i++) { 71 cout << list->val << endl; 72 list = list->next; 73 } 74 }