题目连接:click~
/*题意:将链表中第m到n个结点翻转 */ /** *思路:为更好处理表头和第m个结点,引入root结点,同时记录 * 第m-1个结点。从第m个结点开始遍历至第n个结点,将已经 * 遍历过的结点插入在第m-1个结点后,并保证第m个结点的next * 指向遍历结点的next,以避免链表断裂 */ class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { ListNode *root = new ListNode(0); root->next = head; ListNode *mNode = new ListNode(0); ListNode *pre = root , *curr = head; for(int i = 1; i <= n; i ++) { if(i == m) mNode = curr; //记录第m个结点 if(i < m) pre = curr; //记录第m-1个结点 ListNode *next = curr->next; if(i > m && i <= n) { mNode->next = next; //避免链表断裂 curr->next = pre->next; pre->next = curr; } curr = next; } return root->next; } };
时间: 2024-11-07 03:15:58